2017-05-29 59 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]

希望這有助於你