我有一个叫做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())));