In this article we are going to see about Java 8 Stream Collectors groupingBy with counting and summingInt example program.
GoupbyCount.java
Output
GoupbyCount.java
package com.javatutorialcorner.java8; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class GoupbyCount { public static void main(String[] args) { Listemployees = Arrays.asList( new Employee("Sachin Tendulkar", 41), new Employee("MS Dhoni", 34), new Employee("Rahul Dravid", 40), new Employee("Sourav Ganguly", 40), new Employee("Sachin Tendulkar", 41), new Employee("AB de Villiers", 31), new Employee("Virat Kohli", 28), new Employee("MS Dhoni", 34), new Employee("Rahul Dravid", 40), new Employee("Sourav Ganguly", 40), new Employee("Virat Kohli", 28), new Employee("AB de Villiers", 31), new Employee("Virat Kohli", 28) ); System.out.println("Java 8 Stream Collectors groupingBy to count"); Map counting = employees.stream().collect( Collectors.groupingBy(Employee::getName, Collectors.counting())); System.out.println(counting); System.out.println("Java 8 Stream Collectors groupingBy to find sum"); Map sum = employees.stream().collect( Collectors.groupingBy(Employee::getName, Collectors.summingInt(Employee::getAge))); System.out.println(sum); } }
Output
Java 8 Stream Collectors groupingBy to count
{Rahul Dravid=2, Virat Kohli=3, MS Dhoni=2, Sachin Tendulkar=2, Sourav Ganguly=2, AB de Villiers=2}
Java 8 Stream Collectors groupingBy to find sum
{Rahul Dravid=80, Virat Kohli=84, MS Dhoni=68, Sachin Tendulkar=82, Sourav Ganguly=80, AB de Villiers=62}
0 comments:
Post a Comment