2017-05-22 47 views
-2
final List<Toy> toys = Arrays.asList("new Toy(1)", "new Toy(2)"); 

final List<Item> itemList = toys.stream() 
    .map(toy -> { 
     return Item.from(toy); //Creates Item type 
    }).collect(Collectors.toList); 

以上代碼可用於罰款,並將列出玩具列表中的項目。如何映射到多個元素並收集

我想要做的是這樣的:

final List<Item> itemList = toys.stream() 
    .map(toy -> { 
     Item item1 = Item.from(toy); 
     Item item2 = Item.fromOther(toy); 

     List<Item> newItems = Arrays.asList(item1, item2); 
     return newItems; 
    }).collect(Collectors.toList); 

OR

final List<Item> itemList = toys.stream() 
    .map(toy -> { 
     return Item item1 = Item.from(toy); 
     return Item item2 = Item.fromOther(toy); //Two returns don't make sense but just want to illustrate the idea.  
    }).collect(Collectors.toList); 

所以比較這第一個代碼,第一種方法返回1個項目對象爲每個玩具對象。

我該如何做到這一點,我可以爲每個玩具返回兩個物品對象?

--UPDATE--

final List<Item> itemList = toys.stream() 
    .map(toy -> { 
     Item item1 = Item.from(toy); 
     Item item2 = Item.fromOther(toy); 

     return Arrays.asList(item1,item2); 
    }).collect(ArrayList<Item>::new, ArrayList::addAll,ArrayList::addAll); 
+0

如果你已經找到了解決辦法,不更新與你的問題解。請接受相關的答案。 – VGR

+0

我還沒有找到解決方案 – bob9123

+0

@ bob9123更新後的帖子並不多說。什麼是'BasicRule',你如何映射,你爲什麼需要明確提供?一個最小的可運行的例子將有所幫助 – Eugene

回答

4

你已經這樣做......你只需要flatMap

final List<Item> itemList = toys.stream() 
.map(toy -> Arrays.asList(Item.from(toy),Item.fromOther(toy)) 
.flatMap(List::stream) 
.collect(Collectors.toList()); 

或者你完全刪除映射的建議:

final List<Item> itemList = toys.stream() 
.flatMap(toy -> Stream.of(Item.from(toy),Item.fromOther(toy)))) 
.collect(Collectors.toList()); 
1

如果您希望爲每個玩具返回兩個項目,可能輸出類型應該是List<List<Item>>

List<List<Item>> itemList = 
    toys.stream() 
     .map(toy -> Arrays.asList(Item.from(toy),Item.fromOther(toy))) 
     .collect(Collectors.toList); 

如果你希望每Toy兩個Item s到被收集到同一List<Item>,使用flatMap

List<Item> itemList = 
    toys.stream() 
     .flatMap(toy -> Stream.of(Item.from(toy),Item.fromOther(toy))) 
     .collect(Collectors.toList); 
+0

我寧願讓它成爲一個List但包含兩個元素 – bob9123

+0

@ bob9123在這種情況下,您應該使用'flatMap'而不是'map'。請參閱編輯。 – Eran

相關問題