Implementations of Collector that implement various useful reduction operations, such as accumulating elements into collections, summarizing elements according to various criteria, etc. Here is different ways of java 8 stream group by count with examples like grouping ,counting, filtering, summing, averaging, multi level grouping.

Example 1: Grouping by + Counting

package com.javadeveloperzone;

import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * Created by Lenovo on 30-04-2017.
 */
public class GroupingByCountExample {
    public static void main(String... args) {
        java.util.List<String> strings = Arrays.asList("Zohne", "Redy", "Zohne", "Redy", "Stome");
        java.util.Map<String, Long> nameCount = strings.stream().collect(Collectors.groupingBy(string -> string, Collectors.counting()));
        nameCount.forEach((name, count) -> {
            System.out.println(name + ":" + count);
        });
    }

}

Output

Zohne:2
Stome:1
Redy:2

Example 2: Grouping by + Counting + Filtering

In bellow example we will take only those values whose grouping by count greater than 2. So first we will do grouping and than perform filter on result map than return values.

java.util.Set<String> grupingThanFilter = allWords.stream().collect(Collectors.collectingAndThen(Collectors
 .groupingBy(Function.identity(), Collectors.counting()),map->{
 map.values().removeIf(l -> l<=2);
 return map.keySet();

 }));
grupingThanFilter.forEach(System.out::println);

Output:

Zohne
Redy

Example 3: Grouping by + summingInt

java.util.List<Employee> employees = Employee.getEmployee();
       java.util.Map<String, Integer> designationWiseTotalSalary = employees.stream().collect(Collectors
               .groupingBy(Employee::getDesignation, Collectors.summingInt(Employee::getSalary)));

       designationWiseTotalSalary.forEach((k, v) -> {
           System.out.println(k + " : " + v);
       });

Output:

Sr. Developer : 72000
Developer : 113000
CEO : 100000

Example 4: Grouping by + averagingLong

java.util.List<Employee> employees = Employee.getEmployee();
        java.util.Map<String, Double> designationWiseEvgSalary = employees.stream().collect(Collectors
                .groupingBy(Employee::getDesignation, Collectors.averagingLong(Employee::getSalary)));

        designationWiseEvgSalary.forEach((k, v) -> {
            System.out.println(k + " : " + v);
        });

Output:

Sr. Developer : 72000.0
Developer : 28250.0
CEO : 100000.0

Example 5: Multi Level Grouping by + averagingInt

java.util.List<Employee> employees = Employee.getEmployee();
        java.util.Map<String, java.util.Map<String, Double>> designationGroupByAvg = employees.stream()
                                                                                              .collect(Collectors
                                                                                                      .groupingBy(Employee::getDesignation, Collectors
                                                                                                              .groupingBy(Employee::getGender, Collectors
                                                                                                                      .averagingInt(Employee::getSalary))));
        designationGroupByAvg.forEach((designation, values) -> {
            System.out.println("Designation:" + designation);
            values.forEach((gender, avg) -> {
                System.out.println(gender + ":" + avg);
            });
            System.out.println();
        });

Output:

Designation:Sr. Developer
Male:72000.0

Designation:Developer
Female:24000.0
Male:32500.0

Designation:CEO
Male:100000.0

Employee.java

package com.javadeveloperzone;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by JavaDeveloperZone on 29-04-2017.
 */
public class Employee  {
    private int no;
    private String name;
    private String designation;
    private String gender;
    private int salary;
    private java.util.Set<String> language = new HashSet<String>();

    public Employee(int no, String name, String designation, String gender,int salary) {
        this.no = no;
        this.name = name;
        this.designation = designation;
        this.gender = gender;
        this.salary  = salary;
    }

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDesignation() {
        return designation;
    }

    public void setDesignation(String designation) {
        this.designation = designation;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return this.no + " : " + this.name + " : " + gender + " : " + designation;
    }

    public String addLanguage(String language) {
        this.language.add(language);
        return language;
    }

    public Set<String> getLanguage() {
        return language;
    }

    public static java.util.List<Employee> getEmployee() {
        java.util.List<Employee> employees = new ArrayList<>();
        employees.add(new Employee(1, "Bob", "Developer", "Male",30000));
        employees.add(new Employee(2, "Joy", "Sr. Developer", "Male",72000));
        employees.add(new Employee(3, "John", "CEO", "Male",100000));
        employees.add(new Employee(4, "Bat", "Developer", "Male",35000));
        employees.add(new Employee(5, "Jolly", "Developer", "Female",36000));
        employees.add(new Employee(6, "Bobby", "Developer", "Female",12000));
        return employees;
    }
}

 

 

Ref:

https://stackoverflow.com/questions/30515792/collect-stream-with-grouping-counting-and-filtering-operations

https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html

Was this post helpful?
Let us know, if you liked the post. Only in this way, we can improve us.
Yes
No
Tags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *