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);
如果你已經找到了解決辦法,不更新與你的問題解。請接受相關的答案。 – VGR
我還沒有找到解決方案 – bob9123
@ bob9123更新後的帖子並不多說。什麼是'BasicRule',你如何映射,你爲什麼需要明確提供?一個最小的可運行的例子將有所幫助 – Eugene