Java 8 – Streams API – reduce(), findFirst(), findAny()
This section describes some important operations provided by Streams API – reduce(), findFirst() and findAny().
reduce()
identity – initial value for the accumulator, and also the default result when stream is empty
accumulator – operation to be applied on the elements
combiner – function which combines the results of the accumulators in parallel mode
findFirst()
findAny()
Examples
The examples illustrated below use the following Employee POJO class:
package org.examples;
public class Employee { private String name; private Integer hourRate; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getHourRate() { return hourRate; } public void setHourRate(Integer hourRate) { this.hourRate = hourRate; } public Employee(String name, Integer hourRate) { super(); this.name = name; this.hourRate = hourRate; } @Override public String toString() { return “Employee [name=” + name + “, hourRate=” + hourRate + “]”; } } |
We create a list of Employees to perform operations in the examples:
List<Employee> employees = Arrays.asList(new Employee(“Jack”, 10), new Employee(“Robert”, 50), new Employee(“David”, 30), new Employee(“Abhi”, 20), new Employee(“Daniel”,20), new Employee(“Ankit”,30), new Employee(“Nilton”,40), new Employee(“Joseph”,50)); |
Optional<Employee> emp = employees.stream().reduce ((emp1,emp2)-> emp1.getHourRate()<emp2.getHourRate() ? emp1 : emp2); emp.ifPresent(System.out::println);
|
Output: Employee [name=Jack, hourRate=10] |
Integer totalRate = employees.stream().map(Employee::getHourRate) .reduce(0,(emp1,emp2)->emp1+emp2); System.out.println(totalRate);
|
Output: 250 |
Integer totalRate = employees.stream().map(Employee::getHourRate).parallel() .reduce(0,(emp1,emp2)->emp1+emp2, (emp3,emp4) -> { Thread.currentThread().getName()); return emp3+emp4;
|
Output: combiner called; Thread: ForkJoinPool.commonPool-worker-5 combiner called; Thread: ForkJoinPool.commonPool-worker-7 combiner called; Thread: ForkJoinPool.commonPool-worker-3 combiner called; Thread: main combiner called; Thread: ForkJoinPool.commonPool-worker-3 combiner called; Thread: main combiner called; Thread: main 250 |
Optional<Employee> employee= employees.stream() .filter(emp->emp.getName().startsWith(“A”)) .findFirst(); employee.ifPresent(System.out::println);
|
Output: Employee [name=Abhi, hourRate=20] |
Optional<Employee> employee = employees.stream() .filter(emp->emp.getHourRate()>20) .findAny();
|
Output: Employee [name=Robert, hourRate=50] |
Leave a Reply