Java Stream How to - Get the Max value in a Stream








Question

We would like to know how to get the Max value in a Stream.

Answer

/*from ww w  .j av a  2  s.com*/
import java.util.Arrays;

public class Main {

  public static void main(String[] args) {
    Arrays.asList(1,20,40,4)
    .stream()
    .max(Integer::compareTo)
    .ifPresent(max -> System.out.println("max number: " + max));
  }
}

The code above generates the following result.