我试过这个代码(list
是ArrayList<List<Integer>>
):如何使用Streams将2D列表转换为1D列表?
list.stream().flatMap(Stream::of).collect(Collectors.toList());
,但它不会做任何事情;该列表仍然是一个2D列表。我怎样才能将这个2D列表转换为一维列表?
我试过这个代码(list
是ArrayList<List<Integer>>
):如何使用Streams将2D列表转换为1D列表?
list.stream().flatMap(Stream::of).collect(Collectors.toList());
,但它不会做任何事情;该列表仍然是一个2D列表。我怎样才能将这个2D列表转换为一维列表?
原因是您仍然收到列出的清单是因为当你申请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());
您可以在您的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]
简单的解决方案是:
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(流 - >流)'而不是。 –
工作。 '.flatMap(l - > l.stream())'。为什么这个工作,但'Stream :: of'不? –
'Stream.of' _adds_维度。 –