Learnitweb

Find Maximum Element Using reduce() in Java

Assume a list of integers:

List<Integer> numbers = Arrays.asList(3, 7, 2, 9, 5);

Using reduce()

Integer max = numbers.stream()
    .reduce((a, b) -> a > b ? a : b)
    .orElse(null); // returns null if list is empty

System.out.println(max);

Output:

9

Summary:

  • reduce() combines elements pairwise using a lambda.
  • (a, b) -> a > b ? a : b keeps the larger value each step.
  • .orElse(null) handles empty lists safely.

This is a functional alternative to Collections.max() or stream().max().