Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

grouping list object by attribute using java 8

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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()));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading