Video in progress

Strong Junior 🌊 Streams and lambdas

How do you find the largest or smallest element in a stream, and what do you do when some fields are null?

Use max(comparator) or min(comparator): they return an Optional, because the stream may be empty. If the field being compared can be null, wrap it with Comparator.nullsFirst/nullsLast, otherwise you get an NPE.

📖 Answer

Optional<Employee> top = employees.stream()
        .max(Comparator.comparingInt(Employee::salary));

String name = top.map(Employee::name).orElse("hech kim");

For a numeric field there's another way: mapToInt(Employee::salary).max() returns an OptionalInt, but it gives you just the number, not the employee.

Now null. Say lastLogin is missing for some users:

// NPE: comparing compares a null value with compareTo
users.stream().max(Comparator.comparing(User::lastLogin));

// treat nulls as the smallest
users.stream().max(Comparator.comparing(User::lastLogin,
        Comparator.nullsFirst(Comparator.naturalOrder())));

Writing nullsFirst(Comparator.comparing(User::lastLogin)) is something else: it handles the case where the User object itself is null, not the field. This mix-up is common.

If several elements tie for the maximum, assume it isn't guaranteed which one is returned. If you need a definite choice, add a second criterion with thenComparing.