We are moved to new domain
Click -> www.ehowtonow.com
Thursday, 29 June 2017

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.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) {
  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}


Shop and help us

Flipkart Offer Snapdeal offer Amazon.in offer Amazon.com offer
  • Blogger Comments
  • Facebook Comments
  • Disqus Comments

0 comments:

Post a Comment

Item Reviewed: Java 8 Stream Collectors groupingBy with count and sum Example Rating: 5 Reviewed By: eHowToNow