Over

120,000

Worldwide

Saturday - Sunday CLOSED

Mon - Fri 8.00 - 18.00

Call us

 

Java 8 – Streams API – reduce(), findFirst(), findAny()

Java 8 Streams API – reduce(), findFirst(), findAny()

This section describes some important operations provided by Streams API – reduce(), findFirst() and findAny().

reduce()

 This method combines all elements of the stream into a single result, by repeated application of a combining operation.
 There are three variations of this method which use the following parameters:

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

.

1.Optional<T> reduce(BinaryOperator<T> accumulator)
2.T reduce(T identity, BinaryOperator<T> accumulator)
3.U reduce(U identity, BiFunction<U, ? super T,U> accumulator, BinaryOperator<U> combiner)

.

findFirst()

.

 This method returns the first element from a stream, or no element if the stream is empty.
  If the stream has no encounter order, then any element may be returned.

.

  Optional<T> findFirst()

.

findAny()

.

 This method returns any one element from a stream, or no element if the stream is empty.
 The encounter order in the stream is not considered.

.

     Optional<T> 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));  

.

.

1.This example shows usage of reduce() with accumulator, to find the employee with minimum hour rate.

.

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]

.

.

2.This example shows usage of reduce() with identity and accumulator, to calculate the sum of hour rate of all employees.

.

Integer totalRate =   

                   employees.stream().map(Employee::getHourRate)

                                     .reduce(0,(emp1,emp2)->emp1+emp2);
.

System.out.println(totalRate);

.

Output:

250

.

.

3.This example shows usage of reduce() with identity, accumulator and combiner. Combiner is used while processing large data in parallel mode to improve execution times.

.

Integer totalRate =

          employees.stream().map(Employee::getHourRate).parallel()

                            .reduce(0,(emp1,emp2)->emp1+emp2, (emp3,emp4) ->

                      {
  System.out.println(“combiner called; Thread: ” +

                                            Thread.currentThread().getName());

                        return emp3+emp4;
                       });
System.out.println(totalRate);

.

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

.

.

.

.

4.This example shows usage of findFirst() to return the first employee in the list whose name starts with A.

.

Optional<Employee> employee= employees.stream()

                                      .filter(emp->emp.getName().startsWith(“A”))

                                      .findFirst();

employee.ifPresent(System.out::println);

.

Output:

Employee [name=Abhi, hourRate=20]

.

.

.

5.This example shows usage of findAny() to return any employee which has hour rate greater than 20. The result is not guaranteed here.

.

Optional<Employee> employee = employees.stream()

                                       .filter(emp->emp.getHourRate()>20)

                                       .findAny();
employee.ifPresent(System.out::println);

.

Output:

Employee [name=Robert, hourRate=50]

.

Leave a Reply

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

Working Hours

  • Monday 9am - 6pm
  • Tuesday 9am - 6pm
  • Wednesday 9am - 6pm
  • Thursday 9am - 6pm
  • Friday 9am - 6pm
  • Saturday Closed
  • Sunday Closed