Home > other >  grouping list object by attribute using java 8
grouping list object by attribute using java 8

Time:11-07

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

CodePudding user response:

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()));

CodePudding user response:

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()));
  • Related