Java Stream How to - Use Reduce and Integer.max to get max value in a list








Question

We would like to know how to use Reduce and Integer.max to get max value in a list.

Answer

import java.util.Arrays;
import java.util.List;
//from w w w.  j a  v a  2 s.  c o m
public class Main {
  public static void main(String...args){
    List<Integer> numbers = Arrays.asList(3,4,5,1,2);

    int max = numbers.stream().reduce(0, (a, b) -> Integer.max(a, b));
    System.out.println(max);
    
  }
}

The code above generates the following result.