Many times we have a list of particular object & we want to reduce it to some different type. Here we will take example of List of Employee object. We will reduce it to a single String using reduce with accumulator, identity & combiner.
Reduction operation:
- Iterate list of Employee objects.
- For each Employee object, create a String by concatenating Name & Department.
- Then concatenate all such strings of all employee into single String.
We will use <U> U reduce(U identity, BiFunction<U,? super T,U> accumulator, BinaryOperator<U> combiner) function with 3 arguments.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
package com.itsallbinary.java.java8.lambda; import java.util.ArrayList; import java.util.List; /** * Reduce List of Employees to a String. * * @author itsallbinary * */ public class StreamReduceToDifferentType { public static void main(String[] args) { /* * List of employees */ List<Employee> list = new ArrayList<>(); list.add(new Employee("John", "IT")); list.add(new Employee("Tom", "Service")); list.add(new Employee("Ravi", "Development")); list.add(new Employee("Jimmy", "Management")); /* * With System.out.println in accumulator for understanding. */ String reducedString1 = list.stream().reduce("", (nameDept, employee) -> { System.out.println("nameDept = " + nameDept + " | employee = " + employee); return nameDept = nameDept + " (" + employee.name + "-" + employee.department + ")"; }, (a, b) -> a + b); System.out.println("Final reduced string = " + reducedString1); /* * Without any System.out.println */ String reducedString = list.stream().reduce("", (nameDeptString, employeeObject) -> nameDeptString = nameDeptString + " (" + employeeObject.name + "-" + employeeObject.department + ")", (a, b) -> a + b); System.out.println("Final reduced string = " + reducedString); } } class Employee { String name; String department; public Employee(String name, String department) { super(); this.name = name; this.department = department; } }str |
Output:
1 2 3 4 5 6 |
nameDept = | employee = com.itsallbinary.java.java8.lambda.Employee@61baa894 nameDept = (John-IT) | employee = com.itsallbinary.java.java8.lambda.Employee@449b2d27 nameDept = (John-IT) (Tom-Service) | employee = com.itsallbinary.java.java8.lambda.Employee@5479e3f nameDept = (John-IT) (Tom-Service) (Ravi-Development) | employee = com.itsallbinary.java.java8.lambda.Employee@27082746 Final reduced string = (John-IT) (Tom-Service) (Ravi-Development) (Jimmy-Management) Final reduced string = (John-IT) (Tom-Service) (Ravi-Development) (Jimmy-Management) |