Something peculiar I stumbled upon the other day.
Consider the following code (it collects the distinct word length counts of the given Strings, but that's not important):
static void collectByLambda(Collection<String> list) {
Collection<Integer> collected = list.stream().collect(Collectors.collectingAndThen(
Collectors.groupingBy(String::length),
m -> m.keySet()
));
}
and its equivalent method reference version:
static void collectByMethodReference(Collection<String> list) {
Collection<Integer> collected = list.stream().collect(Collectors.collectingAndThen(
Collectors.groupingBy(String::length),
Map::keySet
));
}
The first (lambda) version does not require you to import java.util.Map to compile, the second one does.
Why is this exactly? I can imagine it's because the second version needs to have access to the Map class at compile time to build the reference; but how does it know that Map#keySet() even exists if it doesn't import Map?