我尝试了这段代码(list
是 ArrayList<List<Integer>>
):
list.stream().flatMap(Stream::of).collect(Collectors.toList());
但这并没有实现任何功能,列表仍然是一个二维列表。我该如何将这个二维列表转换成一个一维列表?
我尝试了这段代码(list
是 ArrayList<List<Integer>>
):
list.stream().flatMap(Stream::of).collect(Collectors.toList());
但这并没有实现任何功能,列表仍然是一个二维列表。我该如何将这个二维列表转换成一个一维列表?
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());
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]
希望这可以帮助你
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]
flatMap(stream -> stream)
。 - Louis Wasserman.flatMap(l -> l.stream())
。为什么这个可行,但是Stream::of
不行呢? - ackStream.of
增加了一个维度。 - Louis Wasserman.flatMap(l -> l.stream()
替换为.flatMap(Collection::stream)
。 - Ousmane D.