Video in progress
Why does the signature of Stream.map() say Function<? super T, ? extends R>? If you write a utility that accepts a function, how do you place the wildcards?
This is the PECS rule: the function takes T (a consumer), so ? super T, and gives R (a producer), so ? extends R. That way you can pass a Function<Object, Integer> or a Predicate<Animal> to a Stream<Dog>. If you leave the wildcards out of your own utility, the caller runs into a confusing compile error.
📖 Answer
Look at the signatures in the JDK:
<R> Stream<R> map(Function<? super T, ? extends R> mapper);
Stream<T> filter(Predicate<? super T> predicate);
Stream<T> sorted(Comparator<? super T> comparator);
The practical benefit is reusing general lambdas:
Predicate<Object> notNull = Objects::nonNull;
Comparator<Number> byDouble = Comparator.comparingDouble(Number::doubleValue);
List<Integer> ids = ...;
ids.stream().filter(notNull).sorted(byDouble).toList(); // works
Now a utility you write yourself:
// bad: accepts only exactly Predicate<T>
static <T> List<T> keep(List<T> list, Predicate<T> p) { ... }
keep(ids, notNull); // compile error: Predicate<Object> != Predicate<Integer>
// right
static <T> List<T> keep(Collection<? extends T> src, Predicate<? super T> p) {
return src.stream().filter(p).collect(Collectors.toList());
}
Easy to remember: a type that goes into the function as a parameter is super, and a type that comes out of the function is extends. Don't put a wildcard on the return type: if you return List<? extends T>, you make the caller's life harder.
In interviews they often ask "why not map(Function<T, R>)?" The answer is exactly the notNull example above: without wildcards you'd have to rewrite general functions for every type.
Sign up to mark studied questions and save your progress.