Let's say I have some stream and want to collect to map like this
stream.collect(Collectors.toMap(this::func1, this::func2));
But I want to skip null keys/values. Of course, I can do like this
stream.filter(t -> func1(t) != null)
.filter(t -> func2(t) != null)
.collect(Collectors.toMap(this::func1, this::func2));
But is there more beautiful/effective solution?
Best Answer
If you want to avoid evaluating the functions
func1
andfunc2
twice, you have to store the results. E.g.This doesn’t make the code shorter and even the efficiency depends on the circumstances. This change pays off, if the costs of evaluating the
func1
andfunc2
are high enough to compensate the creation of temporary objects. In principle, the temporary object could get optimized away, but this isn’t guaranteed.Starting with Java 9, you can replace
new AbstractMap.SimpleImmutableEntry<>(…)
withMap.entry(…)
. Since this entry type disallowsnull
right from the start, it would need filtering before constructing the entry:Alternatively, you may use a pair type of one of the libraries you’re already using (the Java API itself doesn’t offer such a type).