【问题标题】:How to map to multiple elements and collect如何映射到多个元素并收集
【发布时间】:2017-05-22 23:12:25
【问题描述】:
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);

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);

因此与第一个代码相比,第一个方法为每个玩具对象返回一个项目对象。

我如何才能为每个玩具返回两个物品对象?

--更新--

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);

【问题讨论】:

  • 如果您找到了解决方案,请不要用解决方案更新您的问题。改为接受相关答案。
  • 我还没有找到解决办法
  • @bob9123 更新的帖子并没有说太多。什么是BasicRule 以及如何映射以及为什么需要明确提供?一个最小的可运行示例会有所帮助

标签: java java-8 java-stream


【解决方案1】:

你已经这样做了……你只需要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());

【讨论】:

    【解决方案2】:

    如果您希望为每个玩具返回两个项目,也许输出类型应该是List&lt;List&lt;Item&gt;&gt;

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

    如果您希望将每个Toy 中的两个Items 收集到同一个List&lt;Item&gt;,请使用flatMap

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

    【讨论】:

    • 我宁愿它是一个 List 但包含两个元素
    • @bob9123 在这种情况下,您应该使用flatMap 而不是map。见编辑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-06
    • 2018-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多