3

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.

1
  • 1
    Lists are not well suited for this kind of operation. You'd get much better performance with a Guava Multiset. Commented Jun 19, 2018 at 16:42

1 Answer 1

11

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()));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.