Video in progress

Strong Middle 🌊 Streams and lambdas

Why doesn't this code compile, and how do you fix it?

record User(String name, int age) {}

List<User> sorted = users.stream()
        .sorted(Comparator.comparing(u -> u.name()).reversed())
        .toList();

The compiler infers a lambda parameter's type only from the target type. In a .reversed() chain the result of comparing(...) isn't assigned to anything, so u is taken as Object and u.name() isn't found. A method reference, an explicitly typed parameter or an explicit type argument solves the problem.

📖 Answer

The error is roughly: cannot find symbol: method name() in class Object.

The cause: in Java, type inference doesn't work backward along a chain. The type sorted(...) expects applies to the result of reversed(), not to the comparing(...) call. comparing is evaluated on its own, and it has no information about T, so it stays Object.

Without the chain, it works:

.sorted(Comparator.comparing(u -> u.name()))   // here the target type is Comparator<? super User>

Ways to fix it while keeping the chain:

Comparator.comparing(User::name).reversed()                 // the method reference states the type itself
Comparator.comparing((User u) -> u.name()).reversed()       // the parameter type is explicit
Comparator.<User, String>comparing(u -> u.name()).reversed() // the type arguments are explicit

In practice the first is the cleanest. The same problem shows up in lambdas inside thenComparing, so I write complex comparators with method references or as a separate static final Comparator<User> BY_NAME.

In an interview this question tests how well you understand type inference: the expected answer is "the lambda's type isn't in the lambda itself, it comes from the context".