简体   繁体   中英

Using Java 8 streams groupingBy on a list of list of Strings?

I have the following list of strings

List<String> product_a= Arrays.asList("Product A", "Category A", "Price");
List<String> product_b= Arrays.asList("Product A", "Category A", "Price");
List<String> product_c= Arrays.asList("Product B", "Category B", "Price");
List<String> product_d = Arrays.asList("Product C", "Category C", "Price");

Then, I put them in another list

List<List<String>> products = new ArrayList<>();
products.add(product_a);
products.add(product_b);
products.add(product_c);
products.add(product_d);

Using streams, Collectors.groupingBy, Collectors.counting, how can I get the following output? is it possible?

Product A - 2
Product B - 1
Product C - 1

In advance, thank you for your help.

You mean :

Map<String, Long> group = products.stream()
        .collect(Collectors.groupingBy(c -> c.get(0), Collectors.counting()));

group.entrySet().forEach(c -> System.out.println(c.getKey() + " - " + c.getValue()));

Outputs

Product A - 2
Product B - 1
Product C - 1

But I would like to create a class which hold this three information product category price instead of using List for each item.

class Product{
    private String productName;
    private String category;
    private BigDecimal price;

    //constructors getters setters
}

Then fill your products in an List of Product like so :

List<Product> products = new ArrayList<>();
products.add(new Product("Product A", "Category A", new BigDecimal("123")));
products.add(new Product("Product A", "Category A", new BigDecimal("456")));
products.add(new Product("Product B", "Category B", new BigDecimal("696")));
products.add(new Product("Product C", "Category C", new BigDecimal("66")));

Then you grouping can be :

Map<String, Long> group = products.stream()
        .collect(Collectors.groupingBy(Product::getProductName, Collectors.counting()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM