Java 8 Stream Collectors groupingBy with count and sum Example

In this article we are going to see about Java 8 Stream Collectors groupingBy with counting and summingInt example program.

GoupbyCount.java

package com.ehowtonow.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) {
  List employees = 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}


Ask your questions in eHowToNow Forum

Post your technical, non-technical doubts, questions in our site. Get answer as soon as possible, meanwhile you can help others by answering, unanswered questions.
To Ask new Question : Ask Question
Check our existing discussions : Questions & Answers

  1. Java – ToIntFunction Interface
  2. Java 8 Stream Filter with findAny orElse Example
  3. java.util.function Package
  4. Java – BiConsumer Interface
  5. Java – StreamSupport Class
  6. Java – IntFunction Interface
  7. Java – DoubleFunction Interface
  8. Java – IntUnaryOperator Interface
  9. Java – Stream Interface
  10. Java 8 Stream Collectors groupingBy with sort Example
  11. Java – BiPredicate Interface
  12. Java 8 Stream Collectors groupingBy with count and sum Example
  13. Java – Stream.Builder Interface
  14. Java – IntStream Interface
  15. Java – ToDoubleFunction Interface

Be the first to comment

Leave a Reply