Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
776 views
in Technique[技术] by (71.8m points)

java - Stream groupingBy a list of enum types

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can flatMap the group within each Product to the name of the product and then group it by Group mapping the corresponding names 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())));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...