问题
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);
}
}
where Group is an enum
public enum Group {
LEISURE,
SPORT,
FORMALATTIRE,
BABY,
MATERNITY
//...
}
From a list of products I want to create a Map<Group,List<Product>>
Example input:
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));
How can I do it with a List<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]}
回答1:
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())));
回答2:
You can create a stream of Entry<Group,String>
by using flatMap
and then collect them into Map<Group, List<String>>
using Collectors.mapping
productList.stream()
.flatMap(p->p.getGroup()
.stream()
.map(g->new AbstractMap.SimpleEntry<>(g,p.getName()))) // or from jdk 9 you can use Map.entry(g, p.getName());
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
来源:https://stackoverflow.com/questions/58475865/stream-groupingby-a-list-of-enum-types