Group objects based on multiple properties

Viewed 92

I want to group/collect objects based on some properties. The project has some Product objects:

public class Product {
    private String id;
    private String name;
    private ProductFlavor flavor; // enum
    private ProductType productType; // enum
    private ProductCategory category; // enum
}

What I know need to do is make a collection so that the products are combined per Category and per category are combined per productType and then show all possible flavors for that product.

So for example

  • Product 1 has Category 1 and is of type cookie and has flavor vanilla
  • Product 2 has Category 2 and is of type biscuits and has flavor strawberry
  • Product 3 has Category 1 and is of type cookie and has flavor chocolate

To visualize this is a product table that should in this case contain

  • Cookie with a dropdown vanille and chocolate
  • Biscuits with a dropdown strawberry

I started with grouping them by category but then I'm stuck. Because to me it should be a List of product categories with grouped products with possible flavors.

Map<ProductCategory, List<Product>> result = dummies.stream().collect(
        Collectors.groupingBy(
                Product::getCategory,
                TreeMap::new,
                Collectors.mapping(event -> event, Collectors.toCollection(ArrayList::new))
        )
);
1 Answers

is that what You need?

   Map<ProductFlavor,Map<ProductCategory,List<Product>>> byFlavor = products.stream()
        .collect( groupingBy( p -> p.flavor, groupingBy( c -> c.category ) ) ); 

flavor and category must be made accessible or You define getters

Related