Java - Stream Reduced to Optional

Introduction

The following reduce() method returns Optional<T>.

Optional<T> reduce(BinaryOperator<T> accumulator)

The method returns an Optional<T> that wraps the result or the absence of a result.

The following code computes the maximum of integers in a stream:

Demo

import java.util.Optional;
import java.util.stream.Stream;

public class Main {
  public static void main(String[] args) {
    Optional<Integer> max = Stream.of(1, 2, 3, 4, 5).reduce(Integer::max);
    if (max.isPresent()) {
      System.out.println("max = " + max.get());
    } else {//from  w  ww  .j  a  va 2  s . c o  m
      System.out.println("max is not defined.");
    }

  }
}

Result

The following code tries to get the maximum of integers in an empty stream:

Demo

import java.util.Optional;
import java.util.stream.Stream;

public class Main {
  public static void main(String[] args) {
    Optional<Integer> max = Stream.<Integer>empty().reduce(Integer::max);
    if (max.isPresent()) {
      System.out.println("max = " + max.get());
    } else {//from w ww  . j  a v a  2 s  .  c om
      System.out.println("max is not defined.");
    }
  }
}

Result

The following code prints the details of the highest earner in the person's list:

import java.util.Optional;

public class Main {
  public static void main(String[] args) {
    Optional<Person> person = Person.persons().stream().reduce((p1, p2) -> p1.getIncome() > p2.getIncome() ? p1 : p2);
    if (person.isPresent()) {
      System.out.println("Highest earner: " + person.get());
    } else {
      System.out.println("Could not get the highest earner.");
    }

  }
}

Related Topic