antongarakh
antongarakh

Reputation: 690

Grouping by the inner collection element type in collection

I have

List<Shop> shops;

class Shop {
   private Long id;
   private String name;
   private List<Supplier> suppliers;
}

class Supplier {
   private Long id;
   private String supplierName;
}

What I want to get is

Map<Supplier, List<Shop>> supplierShopsMap;

How to do it with Java Streams?

Upvotes: 1

Views: 83

Answers (1)

Mạnh Quyết Nguyễn
Mạnh Quyết Nguyễn

Reputation: 18235

You should override equal() and hashCode() in Supplier class for grouping.

Map<Supplier, List<Shop>> result = shops.stream()
       .flatMap(s -> s.getSuppliers().stream()
                           .map(sup -> new SimpleEntry<>(sup, s))
       .collect(groupingBy(Entry::getKey,                 // This step requires Supplier equal function
                           mapping(Entry::getValue, toList())));

If you cannot modify the Supplier class to support equal() then you must create map of Supplier

Edit

As @jorn vernee pointed out, we can use flatMap directly without collecting into a list first. It's a huge boost

Upvotes: 3

Related Questions