Tuesday, 6 October 2020

How to Use Collectors with Stream API in Java

 
 Collectors 
Collectors use with Stream API in functional Style programming. The java.util.stream.Collectors introduce in java 1.8 version. Collectors provide facility formulate result you want obtain from stream API
 
The java.util.stream.Collectors class provide various collecting method group modify and obtain result from stream.
 
 The static factory method of Collectors class 


Collectors Factory Method               

Return Type

Use 

toList 

List<T>

Gather the all stream element in List 

toSet

Set<T>

Gather the all stream element in Set

toCollection 

Collection<T>

Gather the all stream element in Collection

counting

long

count all stream element

joining

String

Concatenate the string

summingInt                                           

Integer 

Sum the value of an Integer property in the Stream

averagingInt 

Long

Average the value of an Long property in the Stream

summarzingInt 

IntSummaryStatistics

IntSummaryStatistics Collect Summary statistics the value of an Integer property in the Stream such as maximum,minimum,average,total


maxBy 

Optional<T>

Find maximum value of an Integer property in the Stream

minBy 

Optional<T>

Find minimum value of an Integer property in the Stream

groupingBy 

Map<K,List<T>

Group the all stream element based on property value of Stream

 

partitioningBy 

Map<Boolean,List<T>

Partitioning the all stream element in two group by using value of an Integer property in the Stream

reducing 

produce by reduction operation  

                                


Reduce is use reduce Stream into a single starting with initial value and  reduction operation   then iteratively combining it with each item of stream using a BinaryOperator 


Collectors Application 

package in.jk.java8.collectors;

import java.util.Comparator;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import in.jk.java8.Employee;

public class CollectorsApplication {
public static void main(String[] args) {
System.out.println("     Collectors Application :: \n");
List<Employee> empList = Employee.getEmployeeList();
System.out.println(" to List Collectors ");
                List<Employee> employees  null;
employees = empList.stream().filter(emp->emp.getName().equals("J K"))
                                                 .collect(Collectors.toList());
System.out.println("Employee List by toList Collectors :: "+employees);
System.out.println("\n counting Collectors \n ");
                Long employeeCount =0;
employeeCount = empList.stream().filter(emp->emp.getName().equals("J K"))
                                                         .collect(Collectors.counting());
System.out.println("Employee List by counting Collectors :: "+employeeCount);
System.out.println(" \n maxBy and minBy Collectors \n");
Comparator<Employee> comparator = Comparator.comparingInt(Employee::getSalary);
Optional<Employee> maxSalaryEmployee=null;
Optional<Employee> minSalaryEmployee=null;
maxSalaryEmployee = empList.stream().filter(emp->emp.getName().equals("J K"))
                                    .collect(Collectors.maxBy(comparator));
minSalaryEmployee = empList.stream().filter(emp->emp.getName().equals("J K"))
                                            .collect(Collectors.minBy(comparator));
System.out.println("Employee by maxBy Collectors :: "+maxSalaryEmployee);
System.out.println("Employee by minBy Collectors :: "+minSalaryEmployee);
System.out.println(" \nSummarization Collectors \n");
     System.out.println(" \nUse Of Summarization Collectors summingInt, averagingInt,                                 summarizingInt\n");
                int sumOfSalary=0;
                double averageOfSalary=0; 
sumOfSalary= empList.stream().filter(emp->emp.getName().equals("J K"))
                              .collect(Collectors.summingInt(Employee::getSalary));
averageOfSalary = empList.stream().filter(emp->emp.getName().equals("J K"))
                                           .collect(Collectors.averagingInt(Employee::getSalary));
IntSummaryStatistics summaryStatisticsSalary=null;
        summaryStatisticsSalary= empList.stream()
                                                              .filter(emp->emp.getName().equals("J K"))
                                                             .collect(Collectors.summarizingInt(Employee::getSalary));
System.out.println("Employee by summingInt Collectors :: "+sumOfSalary);
System.out.println("Employee by averagingInt Collectors :: "+averageOfSalary);
System.out.println("Employee by summarizingInt Collectors :: "+summaryStatisticsSalary);
System.out.println(" \njoining Collectors \n");
String employeeNames = empList.stream().map(Employee::getName)
                                       .collect(Collectors.joining(","));
System.out.println("Employee Name by joining Collectors :: "+employeeNames);
System.out.println(" \nreducing Collectors \n");
int salarySum = empList.stream()
                .collect(Collectors.reducing(0,Employee::getSalary,(i,j)->i+j));
System.out.println("Employee Salary Sum by reducing Collectors :: "+salarySum);
 
System.out.println(" \ngroupingBy Collectors \n");
Map<String,List<Employee>> employeeMap =null;
employeeMap = empList.stream()
                                                         .collect(Collectors.groupingBy(Employee::getCompany));
System.out.println("Employee grouping by groupingBy Collectors :: ");
employeeMap.entrySet().stream().forEach(System.out::println);
 
 
System.out.println(" \npartitioningBy Collectors \n");
Map<Boolean,List<Employee>> employeePartitionMap =null;
employeePartitionMap = empList.stream()
                .collect(Collectors.partitioningBy(emp->emp.getCompany().equals("Google")));
System.out.println("Employee partitioning by partitioningBy Collectors :: ");
employeePartitionMap.entrySet().stream().forEach(System.out::println);

}

}

Employee .java
package in.jk.java8;

import java.util.ArrayList;
import java.util.List;

public class Employee {
private int empId;
private String name;
private String company;
private int salary;
//Getters and Setters
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}

@Override
public String toString() {
return "Employee [empId=" + empId + ", name=" + name + ", company=" + company + ", salary=" + salary + "]";
}
public static  List<Employee>getEmployeeList() {
List<Employee> empList =new ArrayList<Employee>();
Employee  employee = new Employee();
        employee.setEmpId(1);
        employee.setName("J K");
        employee.setCompany("Google");
        employee.setSalary(1000);
        
        Employee  employee1 = new Employee();
        employee1.setEmpId(2);
        employee1.setName("J K");
        employee1.setCompany("Google");
        employee1.setSalary(2000);
        
        Employee  employee2 = new Employee();
        employee2.setEmpId(3);
        employee2.setName("J K");
        employee2.setCompany("Google");
        employee2.setSalary(3000);
        
        Employee  employee3 = new Employee();
        employee3.setEmpId(4);
        employee3.setName("SHA");
        employee3.setCompany("APAR");
        employee3.setSalary(4000);
        
        Employee  employee4 = new Employee();
        employee4.setEmpId(5);
        employee4.setName("HM");
        employee4.setCompany("PAYTM");
        employee4.setSalary(5000);
        
        Employee  employee5 = new Employee();
        employee5.setEmpId(5);
        employee5.setName("HM");
        employee5.setCompany("APAR");
        employee5.setSalary(6000);
        
        Employee  employee6 = new Employee();
        employee6.setEmpId(6);
        employee6.setName("JK");
        employee6.setCompany("APAR");
        employee6.setSalary(7000);
        
        Employee  employee7 = new Employee();
        employee7.setEmpId(7);
        employee7.setName("JK");
        employee7.setCompany("JET BRAINS");
        employee7.setSalary(8000);
        
        Employee  employee8 = new Employee();
        employee8.setEmpId(8);
        employee8.setName("AJ");
        employee8.setCompany("APAR");
        employee8.setSalary(9000);
        
        Employee  employee9 = new Employee();
        employee9.setEmpId(8);
        employee9.setName("AJ");
        employee9.setCompany("ADOBE");
        employee9.setSalary(10000);
        
        empList.add(employee);
        empList.add(employee1);
        empList.add(employee2);
        empList.add(employee3);
        empList.add(employee4);
        empList.add(employee5);
        empList.add(employee6);
        empList.add(employee7);
        empList.add(employee8);
        empList.add(employee9);
return empList;
}
}

 Ouput in console....
 
 Collectors Application :: 

 to List Collectors 
Employee List by toList Collectors :: [Employee [empId=1, name=J K, company=Google, salary=1000], Employee [empId=2, name=J K, company=Google, salary=2000], Employee [empId=3, name=J K, company=Google, salary=3000]]

 counting Collectors 
 
Employee List by counting Collectors :: 3
 
 maxBy and minBy Collectors 

Employee by maxBy Collectors :: Optional[Employee [empId=3, name=J K, company=Google, salary=3000]]
Employee by minBy Collectors :: Optional[Employee [empId=1, name=J K, company=Google, salary=1000]]
 
Summarization Collectors 

 
Use Of Summarization Collectors summingInt,averagingInt,summarizingInt

Employee by summingInt Collectors :: 6000
Employee by averagingInt Collectors :: 2000.0
Employee by summarizingInt Collectors :: IntSummaryStatistics{count=3, sum=6000, min=1000, average=2000.000000, max=3000}
 
joining Collectors 

Employee Name by joining Collectors :: J K,J K,J K,SHA,HM,HM,JK,JK,AJ,AJ
 
reducing Collectors 

Employee Salary Sum by reducing Collectors :: 55000
 
groupingBy Collectors 

Employee grouping by groupingBy Collectors :: 
Google=[Employee [empId=1, name=J K, company=Google, salary=1000], Employee [empId=2, name=J K, company=Google, salary=2000], Employee [empId=3, name=J K, company=Google, salary=3000]]
PAYTM=[Employee [empId=5, name=HM, company=PAYTM, salary=5000]]
ADOBE=[Employee [empId=8, name=AJ, company=ADOBE, salary=10000]]
JET BRAINS=[Employee [empId=7, name=JK, company=JET BRAINS, salary=8000]]
APAR=[Employee [empId=4, name=SHA, company=APAR, salary=4000], Employee [empId=5, name=HM, company=APAR, salary=6000], Employee [empId=6, name=JK, company=APAR, salary=7000], Employee [empId=8, name=AJ, company=APAR, salary=9000]]
 
partitioningBy Collectors 

Employee partitioning by partitioningBy Collectors :: 
false=[Employee [empId=4, name=SHA, company=APAR, salary=4000], Employee [empId=5, name=HM, company=PAYTM, salary=5000], Employee [empId=5, name=HM, company=APAR, salary=6000], Employee [empId=6, name=JK, company=APAR, salary=7000], Employee [empId=7, name=JK, company=JET BRAINS, salary=8000], Employee [empId=8, name=AJ, company=APAR, salary=9000], Employee [empId=8, name=AJ, company=ADOBE, salary=10000]]
true=[Employee [empId=1, name=J K, company=Google, salary=1000], Employee [empId=2, name=J K, company=Google, salary=2000], Employee [empId=3, name=J K, company=Google, salary=3000]]



No comments:

Post a Comment