I have a Product class:
class Product {
String name;
List group;
//more fields, getters, setters
public Product(String 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> 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> 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())));