Java Stream reduce without default value

Introduction

Compute the maximum of integers in a stream.

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 {/* w w w. ja va2 s.  co  m*/
      System.out.println("max is not  defined.");
    }

    
  }
}

Sum on empty stream using reduce().


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   www  .  j  a  va 2 s.c  o m*/
      System.out.println("max is not defined.");
    }
  }
}



PreviousNext

Related