max() is a terminal Stream operation that returns the largest element in the stream, according to a supplied Comparator, wrapped in an Optional.
Key Points: • max(Comparator) requires a comparator even for Comparable types - Integer::compare or Comparator.naturalOrder() both work. • The result is an Optional<T> because an empty stream has no maximum, avoiding a null or exception in that case. • For primitive streams (IntStream, etc.), max() returns an OptionalInt/OptionalLong/OptionalDouble instead and needs no comparator. • max() must traverse the whole stream, unlike short-circuiting operations like findFirst(). • For custom objects, passing Comparator.comparing(Field::getter) lets you find the max by a specific property.
Example: Given the list [4, 9, 2, 7], calling max(Integer::compare) returns an Optional containing 9, the largest value.
Code Example:
Optional<Integer> max = numbers.stream()
.max(Integer::compare);Interview Tip: A concise interview answer is:
"max(Comparator) scans the whole stream and returns the largest element wrapped in an Optional, so I don't have to handle an empty stream with a null check. For primitive streams like IntStream, max() returns an OptionalInt directly with no comparator needed."