我有一个叫做Food的类:

public class Food {
    private Collection<FoodToFoodGroup> foodToFoodGroups;
    //getters and setters
}


FoodToFoodGroup看起来像这样:

public class FoodToFoodGroup {
    private Food food;
    private FoodGroup foodGroup;
    //getters and setters
}


最后,每个FoodGroup都有一个名称:

public class FoodGroup {
    private String name;
    //getters and setters
}


这些类都是通过休眠映射的所有实体。我通过调用Food获得了数据库中所有foodRepository.findAll()实体的集合,并且试图将所有Food实例按其FoodGroup的名称进行分组,以便最终以。我试图通过Stream API进行此操作,但无法提出使用Map<String, Collection<Food>>收集器进行此操作的方法。

Map<String, Collection<Food>> foodsByFoodGroupName =
    foodRepository.findAll().stream()
        .collect(Collectors.groupingBy(
            //what goes here?
        ));


请注意,一个Collectors.groupingBy可以位于多个Food中,因此我需要多个FoodGroup中的任何Food才能在生成的FoodGroup中的多个Collection中显示。 Stream API和Map是否可以实现?



如果我有以下食物:

Food: Pimento Cheese
    - FoodToFoodGroups: [
        - FoodGroup: cheese,
        - FoodGroup: dairy
      ]
Food: Chocolate Milk
    - FoodToFoodGroups: [
        - FoodGroup: milk,
        - FoodGroup: dairy
      ]


我希望生成的Collectors.groupingBy()看起来像这样:

Key: cheese
    - Collection<Food>: [Pimento Cheese]
Key: milk
    - Collection<Food>: [Chocolate Milk]
Key: dairy
    - Collection<Food>: [Pimento Cheese, Chocolate Milk]

最佳答案

这是您要找的东西吗

foodRepository.findAll().stream()
     .map(Food::getFoodToFoodGroup)
     .flatMap(Collection::stream)
     .collect(Collectors.groupingBy(
         f -> f.getFoodGroup().getName(),
         HashMap::new,
         Collectors.mapping(FoodToFoodGroup::getFood, Collectors.toList())));

10-05 21:24