如何使用Streams将2D列表转换为1D列表?

时间:2017-05-29 23:37:50

标签: java list java-8 java-stream

我已尝试过此代码(listArrayList<List<Integer>>):

list.stream().flatMap(Stream::of).collect(Collectors.toList());

但它没有做任何事情;该列表仍然是2D列表。如何将此2D列表转换为1D列表?

3 个答案:

答案 0 :(得分:6)

您仍在接收列表列表的原因是因为当您应用Stream::of时,它会返回现有列表的新流。

当你执行Stream::of时,就像拥有{{{1,2}}, {{3,4}}, {{5,6}}}一样,当你执行flatMap时,就像这样做:

{{{1,2}}, {{3,4}}, {{5,6}}} -> flatMap -> {{1,2}, {3,4}, {5,6}}
// result after flatMap removes the stream of streams of streams to stream of streams

而是您可以使用.flatMap(Collection::stream)来获取流,例如:

{{1,2}, {3,4}, {5,6}}

并将其转换为:

{1,2,3,4,5,6}

因此,您可以将当前的解决方案更改为:

List<Integer> result = list.stream().flatMap(Collection::stream)
                           .collect(Collectors.toList());

答案 1 :(得分:1)

您可以在 recentone.move(to_folder=target_folder) 中使用x.stream()。像,

flatMap

哪些输出(我认为你想要的)

ArrayList<List<Integer>> list = new ArrayList<>();
list.add(Arrays.asList((Integer) 1, 2, 3));
list.add(Arrays.asList((Integer) 4, 5, 6));
List<Integer> merged = list.stream().flatMap(x -> x.stream())
        .collect(Collectors.toList());
System.out.println(merged);

答案 2 :(得分:1)

简单的解决方案是:

List<List<Integer>> listOfLists = Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3, 4));
List<Integer> faltList = listOfLists.
        stream().flatMap(s -> s.stream()).collect(Collectors.toList());
System.out.println(faltList);

答案: [1, 2, 3, 4]

希望这有助于你