如何使用Streams将二维列表转换为一维列表?

7

我尝试了这段代码(listArrayList<List<Integer>>):

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

但这并没有实现任何功能,列表仍然是一个二维列表。我该如何将这个二维列表转换成一个一维列表?


1
请使用 flatMap(stream -> stream) - Louis Wasserman
那个可行。.flatMap(l -> l.stream())。为什么这个可行,但是 Stream::of 不行呢? - ack
1
Stream.of 增加了一个维度。 - Louis Wasserman
2
@GusChambers 如果你想保留方法引用,可以将.flatMap(l -> l.stream()替换为.flatMap(Collection::stream) - Ousmane D.
3个回答

7
由于您仍然收到列表的列表,原因是当您应用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());

2
简单的解决方案是:
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]

希望这可以帮助你


1
你可以在 flatMap 中使用 x.stream()。例如,
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);

输出结果(就像我认为你想要的那样)

[1, 2, 3, 4, 5, 6]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接