min() — returns Optional with the minimum element. max() — returns Optional with the maximum element. They are logical opposites using the same Comparator-based selection mechanism.
min():
Optional<T>.Optional.empty().1Optional<Integer> min = numbers.stream()2 .min(Integer::compareTo);3Optional<Integer> min = numbers.stream()4 .min(Comparator.naturalOrder());
max():
Optional<T>.Optional.empty().1Optional<Integer> max = numbers.stream()2 .max(Integer::compareTo);3Optional<Integer> max = numbers.stream()4 .max(Comparator.naturalOrder());
Both:
1// Find longest string2Optional<String> longest = words.stream()3 .max(Comparator.comparing(String::length));45// Find oldest person6Optional<Person> oldest = people.stream()7 .min(Comparator.comparing(Person::getAge));
Performance considerations:
IntStream.min() which returns OptionalInt — no boxing.IntSummaryStatistics is more efficient.1// Single pass for both min and max2IntSummaryStatistics stats = numbers.stream()3 .mapToInt(Integer::intValue)4 .summaryStatistics();5int min = stats.getMin();6int max = stats.getMax();
Key difference: