2017-05-29 61 views
6

我试过这个代码(listArrayList<List<Integer>>):如何使用Streams将2D列表转换为1D列表?

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

,但它不会做任何事情;该列表仍然是一个2D列表。我怎样才能将这个2D列表转换为一维列表?

+1

使用'flatMap(流 - >流)'而不是。 –

+0

工作。 '.flatMap(l - > l.stream())'。为什么这个工作,但'Stream :: of'不? –

+1

'Stream.of' _adds_维度。 –

回答

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

您可以在您的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] 
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]

希望这有助于你