How to group by java 8 and collect ids from parent

谁说胖子不能爱 提交于 2020-06-29 04:53:58

问题


I have a class A

Company {
  String name;
  Logo logo;
}

Logo {
  int color; //can have values=1 (green),2 (red),3 (blue) ...
  String name;
  String address;
}

Output needed : for each type 1,2,3 Group all instances of Logo by color. For each such group what were A.id Give me companies by their color logos. E.g. which companies have logo red?

I tried following

Input
List<Company> company = {//initialization}

company.stream().map(e -> e.getLogo())
          .collect(Collectors.groupingBy(e -> {Logo b = new Logo(); 
                                               b.setType(e.getType(); 
                                               return b;}, Collectors.counting()))

This produces a map of Logo and count How do I get names of Company?


回答1:


If you were to look for all companies given a color of their logo, you shall group as:

Map<Integer, List<Company>> collect = company.stream()
        .collect(Collectors.groupingBy(e -> e.getLogo().getColor()));

Just in case, just the count of such values matte, you should then use Collectors.counting such as:

Map<Integer, Long> count = company.stream()
        .collect(Collectors.groupingBy(e -> e.getLogo().getColor(),
                Collectors.counting()));

In short, do not map the stream if you want the values to be of type Company itself.

Edit: Based on comments, if the idea is to convert Company to its name you can map once grouped. Using Collectors.mapping such as :

Map<Integer, List<String>> collect = company.stream()
        .collect(Collectors.groupingBy(e -> e.getLogo().getColor(), 
                        Collectors.mapping(Company::getName, Collectors.toList())));



回答2:


You can use groupingby collector and then mapping collector.

companis.stream()
      .collectors(Collectors.groupingBy (c->c.getLogo().getColor(),
  Collectors.mapping (Company::getName,Collectors.toList()));


来源:https://stackoverflow.com/questions/61538869/how-to-group-by-java-8-and-collect-ids-from-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!