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

Alexis C.
  • 91,686
  • 21
  • 171
  • 177
Glad Boy
  • 11
  • 1

2 Answers2

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()));
Thiyagu
  • 17,362
  • 5
  • 42
  • 79
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()));
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156