sakura
sakura

Reputation: 422

How to group by java 8 and collect ids from parent

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?

Upvotes: 1

Views: 1633

Answers (2)

Naman
Naman

Reputation: 31868

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

Upvotes: 2

Hadi
Hadi

Reputation: 17289

You can use groupingby collector and then mapping collector.

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

Upvotes: 1

Related Questions