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]}
See Question&Answers more detail:
os