JAVA 8 – Collectors only in 15 mins with code Example

import Util.Employee;

import java.util.*;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
//print names of emp
System.out.println(“1. Collectors.toList()/Collectors.toSet() : Names of employee :”);
Employee emp = new Employee();
List<Employee> empList = emp.getEmpList();
List<String> empNames = empList.stream().map(Employee::getName).collect(Collectors.toList());
empNames.forEach(System.out::println);

//Returns a Collector that accumulates the input elements into a new Collection
System.out.println(“2. Collectors.toCollection(supplier): Names of employee in treeSet :”);
Set<String> empNameSet = empList.stream().map(Employee::getName).collect(Collectors.toCollection(TreeSet::new));
empNameSet.forEach(System.out::println);

System.out.println(“3. Collectors.joining()/Collectors.joining(CharSequence delimiter)/Collectors.joining(CharSequence delimiter, prefix, suffix): Convert elements to string :”);
String joinEmpNames = empList.stream().map(e -> e.getName()).collect(Collectors.joining(“,”, “My Dear”, “Good Morning”));
System.out.println(“Join all emp names : ” + joinEmpNames);

System.out.println(“4. Collectors.summingDouble(Function)/Collectors.summingInt(Function)/Collectors.summingLong(Function) : Total Salary:”);
Double totalSal = empList.stream().collect(Collectors.summingDouble(Employee::getSalary));
System.out.println(“totalSal is : ” + totalSal);

//5. Collectors.averagingInt(Function)/Collectors.averagingDouble(Function)/Collectors.averagingLong(Function)
Double avgSal = empList.stream().collect(Collectors.averagingDouble(Employee::getSalary));
System.out.println(“5. Average salary is : ” + avgSal);

//6. Collectors.reducing(Identity , BinaryOperator)
Long totalSalByReduce = empList.stream().map(e -> e.getSalary()).reduce(0L, Long::sum);
BinaryOperator<Long> binaryOperator = (a, b) -> a + b;
Long totalSalByReduce1 = empList.stream().map(e -> e.getSalary()).reduce(0L, binaryOperator);
Optional<Long> totalSalByReduce2 = empList.stream().map(Employee::getSalary).collect(Collectors.reducing(binaryOperator));
Long totalSalByReduce3 = empList.stream().map(Employee::getSalary).collect(Collectors.reducing(10L, binaryOperator));
System.out.println(“6. totalSalByReduce is : ” + totalSalByReduce + “:” + totalSalByReduce1 + “:” + totalSalByReduce2.orElse(null)+ “:”+totalSalByReduce3);

//group emp by dept
System.out.println(“7. Collectors.groupingBy(Function): Group by dept:”);

/*The groupingByConcurrent() method in Java’s Stream API is used to group elements of a stream concurrently. This means that the grouping operation will be performed in parallel, which can significantly improve performance for large streams.
On the other hand, groupingBy() is a sequential operation. It processes the elements of the stream one by one, grouping them as it goes.
The main difference between the two is in their performance characteristics. groupingByConcurrent() can provide significant performance improvements for large streams, as it can process the elements in parallel. However, it’s important to note that the order of elements in the result may not match the order in the original stream.
If the order of elements in the result is important, you should use groupingBy() instead. It processes the elements in the order they appear in the stream, and the order of elements in the result will match the order in the original stream.
In summary, if performance is a concern and you have a large stream, use groupingByConcurrent(). If the order of elements in the result is important, use groupingBy().*/

Map<String, List<Employee>> groupByDept = empList.stream().collect(Collectors.groupingBy(Employee::getDept));
System.out.println(groupByDept);
//compute sum of salaries by dept
System.out.println(“Collectors.groupingBy(Function, Collectors): sum salary by dept:”);
Map<String, Double> salaryByDept = empList.stream().collect(Collectors.groupingBy(Employee::getDept,
Collectors.summingDouble(Employee::getSalary)));

System.out.println(“Collectors.groupingByConcurrent(Function, Collectors): sum salary by dept:”);
Map<String, Double> salaryByDept1 = empList.stream().collect(Collectors.groupingByConcurrent(Employee::getDept,
Collectors.summingDouble(Employee::getSalary)));
System.out.println(“salary by dept: ” + salaryByDept + “:” + salaryByDept1);

//8. Partition emp by rating
System.out.println(“8. Collectors.partitionBy(): returns a Map<Boolean, List<T>>”);

Map<Boolean, List<Employee>> eligibleEmpForPromotion = empList.stream().collect(Collectors.partitioningBy(e -> e.getRating() > 2));
System.out.println(eligibleEmpForPromotion);

/*9. The Collectors.mapping(Function, Collector) method in Java’s java.util.stream.Collectors class is used to transform the elements of a stream
into another kind of result. It takes two parameters: a function that performs the transformation,
and a collector that accumulates the transformed elements.*/
System.out.println(“9. Collectors.mapping(Function, Collector)”);
List<String> strNames = empList.stream().collect(Collectors.mapping(e -> e.getName(), Collectors.toList()));
System.out.println(strNames);

/*10. Collectors.collectingAndThen(Collector, Function) used to perform a final transformation on the result of a reduction operation. It takes two parameters: a collector that performs the reduction, and a function that performs the final transformation.*/
//Convert in list and return 4th emprecord from emplList
System.out.println(“10. Collectors.collectingAndThen(Collector, Function)”);
Employee emp4thRow = empList.stream().collect(Collectors.collectingAndThen(Collectors.toList(), e -> e.get(3)));
System.out.println(emp4thRow);

//join all names and return a String
String empNamesJoin = empList.stream().map(e -> e.getName()).collect(Collectors.collectingAndThen(Collectors.joining(“,”), names -> “Names: ” + names));
System.out.println(empNamesJoin);

//11. Collectors.counting()
Long noOfEmps = empList.stream().collect(Collectors.counting());
System.out.println(“no of employees: ” + noOfEmps);

//12. Collectors.minBy(Comparator)
Optional<Employee> minEmp = empList.stream().collect(Collectors.minBy(Comparator.comparing(Employee::getName)));
System.out.println(“minEmp : ” + minEmp);

//13. Collectors.maxBy(Comparator)
Optional<Employee> maxEmp = empList.stream().collect(Collectors.maxBy(Comparator.comparing(Employee::getName)));
System.out.println(“maxEmp : ” + maxEmp);

//14. toMap(Function, Function),
//toMap(Function, Function, BinaryOperator),
// toMap(Function, Function, BinaryOperator, Supplier),
// toConcurrentMap(Function, Function) //If you need a thread-safe map, you should use ConcurrentHashMap, which is a class that implements ConcurrentMap.

Map<Integer, Employee> empMap = empList.stream().collect(Collectors.toMap(Employee::getEmpId, e -> e,
(old, n) -> n, TreeMap::new));
System.out.println(“Emp Map by toMap : ” + empMap);
Map<Integer, Employee> empMap1 = empList.stream().collect(Collectors.toConcurrentMap(Employee::getEmpId, e -> e,
(old, n) -> n));
System.out.println(“Emp Map by toConcurrentMap : ” + empMap1);
/*we have a list of emp. We create a Map where id is a key and its emp object is the value.
The Collectors.toMap() method takes a Function to extract the key, a Function to extract the value,
a BinaryOperator to handle collisions (when two words have the same key), and a Supplier to create a new map.
The TreeMap is used to sort the elements by key. */

//15. Collectors.summarizingInt(Function)/Collectors.summarizingLong(Function)/Collectors.summarizingDouble(Function)
/*We calculate the count, sum, min, max, and average of the numbers using Collectors.summarizingInt(). The result is
a IntSummaryStatistics object that contains these values.*/

LongSummaryStatistics stats = empList.stream().map(e -> e.getSalary()).collect(Collectors.summarizingLong(Long::longValue));
System.out.println(“Count: ” + stats.getCount());
System.out.println(“Sum: ” + stats.getSum());
System.out.println(“Min: ” + stats.getMin());
System.out.println(“Max: ” + stats.getMax());
System.out.println(“Average: ” + stats.getAverage());

}
}