0

I have data like this:

[
   {
      "category":"Fruits",
      "name":"Apple"
   },
   {
      "category":"Fruits",
      "name":"Manggo"
   },
   {
      "category":"Vegetables",
      "name":"Water Spinach"
   }
]

I want to grouping by java 8, I've tried with :

Map<String, List<MyData>> myData
    = list.stream().collect(Collectors.groupingBy(d -> d.getCategory()));

But the result is not what I need. Because the result I expected was Fruits = 2, Vegetables = 1

0

2 Answers 2

2

Based on the result you're after, you'll need to use a groupingBy() collector together with a counting() collector:

Map<String, Long> soldCopiesStats = list
    .stream() 
    .collect(Collectors.groupingBy(MyData::getCategory, Collectors.counting()));
Sign up to request clarification or add additional context in comments.

Comments

2

You can use Collectors.counting as the downstream collector of groupingBy to get the count in each group.

Map<String, Long> myData = list.stream()
        .collect(Collectors.groupingBy(d -> d.getCategory(), Collectors.counting()));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.