What is the Stream max() method in Java?

The Stream max() method will return an Optional that contains the largest value of the stream. The largest values are evaluated based on the passed Comparator argument.

  • If the stream is empty, then an empty Optional is returned.
  • If the largest value returned is null, then NullPointerException is thrown.
  • The max method is a terminal operationThe stream cannot be used after this is called..

Example

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class Main {
public static void main(String[] args)
{
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, -10);
Optional<Integer> max;
max = list
.stream()
.max((a, b) -> a - b );
System.out.println("The list is " + list);
System.out.println("Maximum value of the list is " + max.get());
}
}

In the above code, we have used the Stream max() method on the list stream by passing a comparator to get the largest value of the list. The largest value can be retrieved by calling the get method of the returned Optional.

Example with passing comparator

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Comparator;
public class Main {
public static void main(String[] args)
{
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, -10);
Comparator<Integer> getMax;
getMax = new Comparator<Integer>() {
@Override
public int compare(Integer num1, Integer num2) {
return num1 - num2;
}
};
Optional<Integer> max;
max = list
.stream()
.max(getMax);
System.out.println("The list is " + list);
System.out.println("Maximum value of the list is " + max.get());
}
}

In the above code, we have created a getMax comparator and passed it to the max function, which will call return an Optional with the max value.

Free Resources