如何映射到多个元素并收集

bob*_*123 2 java java-8 java-stream

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);
Run Code Online (Sandbox Code Playgroud)

上面的代码可以正常工作,并将从玩具列表中生成项目列表。

我想做的是这样的:

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);
Run Code Online (Sandbox Code Playgroud)

或者

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);
Run Code Online (Sandbox Code Playgroud)

因此,将其与第一个代码进行比较,第一种方法为每个玩具对象返回 1 个 Item 对象。

我如何制作它以便我可以为每个玩具返回两个项目对象?

- 更新 -

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);
Run Code Online (Sandbox Code Playgroud)

Eug*_*ene 8

你已经在这样做了……你只需要 flatMap

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

或者您完全按照建议删除映射:

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