流分组按枚举类型列表

时间:2019-10-20 18:12:45

标签: java java-stream grouping

我有一个Product类:

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是枚举

public enum Group {
    LEISURE,
    SPORT,
    FORMALATTIRE,
    BABY,
    MATERNITY
    //...
}

我要从一个产品列表中创建一个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));

如果组像名字一样是一个字段,我可以这样做:

productList.stream().collect(Collectors.groupingBy(Product::getName));

如何使用List<Group>来做到这一点?

预期结果如下所示,其中对productList中存在的每个组,映射到在其字段group中具有该组的产品列表

{MATERNITY=[A], FORMALATTIRE=[D, F], LEISURE=[B, C, D, E, F], SPORT=[B, C, D, E], BABY=[A, B]}

2 个答案:

答案 0 :(得分:2)

您可以使用Entry<Group,String>创建flatMap流,然后使用Map<Group, List<String>>将它们收集到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())));

答案 1 :(得分:2)

您可以将flatMap中的组Product与产品name进行组合,然后通过Group将其分组,将相应的name映射为值。如:

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())));

或者要获得组到产品列表的映射,可以用以下公式表示:

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())));