Stream groupingBy a list of enum types

前端 未结 2 1963
旧巷少年郎
旧巷少年郎 2021-01-23 01:15

I have a Product class:

class Product {
    String name;
    List group;
    //more fields, getters, setters
    public Product(String name, Group..         


        
相关标签:
2条回答
  • 2021-01-23 02:10

    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())));
    
    0 讨论(0)
  • 2021-01-23 02:13

    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())));
    
    0 讨论(0)
提交回复
热议问题