流分组按枚举类型列表 [英] Stream groupingBy a list of enum types
问题描述
我有一个Product类:
I have a Product class:
class Product {
String name;
List<Group> group;
//more fields, getters, setters
public Product(String name, Group... group) {
this.name = name;
this.group = Arrays.asList(group);
}
}
其中Group是一个枚举
where Group is an enum
public enum Group {
LEISURE,
SPORT,
FORMALATTIRE,
BABY,
MATERNITY
//...
}
我要从产品列表中创建一个Map<Group,List<Product>>
From a list of products I want to create a Map<Group,List<Product>>
示例输入:
List<Product> productList = new ArrayList<>();
productList.add(new Product("A", Group.BABY, Group.MATERNITY));
productList.add(new Product("B", Group.BABY, Group.LEISURE, Group.SPORT));
productList.add(new Product("C", Group.SPORT, Group.LEISURE));
productList.add(new Product("D", Group.LEISURE, Group.SPORT, Group.FORMALATTIRE));
productList.add(new Product("E", Group.SPORT, Group.LEISURE));
productList.add(new Product("F", Group.FORMALATTIRE, Group.LEISURE));
如果组像名称一样是一个字段,我可以这样做:
If group was a single field just like name I could do:
productList.stream().collect(Collectors.groupingBy(Product::getName));
如何使用List<Group>
来做到这一点?
How can I do it with a List<Group>
?
预期结果如下所示,其中对productList中存在的每个组,映射到在其字段group
Expected result is something like below, where for each group which exists in the productList a mapping to a list of products having this group in their field group
{MATERNITY=[A], FORMALATTIRE=[D, F], LEISURE=[B, C, D, E, F], SPORT=[B, C, D, E], BABY=[A, B]}
推荐答案
您可以将每个Product
中的组flatMap
映射到产品的name
,然后通过Group
映射相应的
You can flatMap
the group within each Product
to the name
of the product and then group it by Group
mapping the corresponding name
s as value. Such as:
Map<Group, List<String>> groupToNameMapping = productList.stream()
.flatMap(product -> product.getGroup().stream()
.map(group -> new AbstractMap.SimpleEntry<>(group, product.getName())))
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
或者要获得组到产品列表的映射,可以用以下公式表示:
or to get a mapping of the group to list of product, you can formulate the same as:
Map<Group, List<Product>> groupToProductMapping = productList.stream()
.flatMap(product -> product.getGroup().stream()
.map(group -> new AbstractMap.SimpleEntry<>(group, product)))
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
这篇关于流分组按枚举类型列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!