In this Java 8 Stream Collectors groupingby post, we will show you how to use Stream Collectors to group by, count, sum and sort a List that is offered by the Java 8 Collectors API. The Java 8 Stream API lets us process collections of data in a declarative way.
Let’s dig deeper via various examples:
1. Group by, Count and Sort
Group by a List and display the total count of it. Then add sorting that result .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public static void main(String[] args) { List<String> languages = Arrays.asList("java", "nodejs", "Java", "php", "C#", "c#", "JAVA"); Map<String, Long> result = languages.stream().map(String::toLowerCase) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); System.out.println(result); Map<String, Long> result1 = new LinkedHashMap<>(); // Sort a map and add to result1 result.entrySet().stream().sorted(Map.Entry.<String, Long>comparingByValue().reversed()) .forEachOrdered(e -> result1 .put(e.getKey(), e.getValue())); System.out.println(result1); } |
Output
1 2 |
{c#=2, java=3, php=1, nodejs=1} {java=3, c#=2, php=1, nodejs=1} |
2. Group by, Count and Sort on a list of objects
We have a pojo as below
1 2 3 4 5 6 |
public class People { private int age; private String gender; private String name; } |
Group by the name and Count or Sum the age on the people list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public static void main(String[] args) { List<People> peoples = Arrays.asList(new People(30,"M","Mr A"), new People(24,"M","Mr B"), new People(31,"M","Mr B")); Map<String, Long> count = peoples.stream() .collect(Collectors.groupingBy(People::getName, Collectors.counting())); System.out.println(count); Map<String, Integer> sum = peoples.stream().collect( Collectors.groupingBy(People::getName, Collectors.summingInt(People::getAge))); System.out.println(sum); } |
Output
1 2 |
{Mr A=1, Mr B=2} {Mr A=30, Mr B=55} |
Group by Price and Collectors.mapping example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public static void main(String[] args) { List<People> peoples = Arrays.asList(new People(30,"M","Mr A"), new People(31,"M","Mr B"), new People(31,"M","Mr C")); //grouping by age Map<Integer, List<People>> ageMap = peoples.stream() .collect(Collectors.groupingBy(People::getAge)); System.out.println(ageMap); //grouping by age and convert List to Set using Collectors mapping Map<Integer, Set<String>> ageSet = peoples.stream().collect( Collectors.groupingBy(People::getAge, Collectors.mapping(People::getName, Collectors.toSet()))); System.out.println(ageSet); } |
Output
That’s all about Java 8 Stream Collectors groupingby examples.
References
Collectors (Java Platform SE 8 )
Download complete source code, click link below
Java8StreamCollectors.zip (273 downloads)