Using java 8 streams I want to convert a list into a map like described in the solution to Java 8 List<V> into Map<K, V>. However, I want to filter to remove entries with certain keys (for instance if the key is null) without doing the conversion of the value to a key twice.
For example I could do the filtering prior to collect such as
Map<String, Choice> result =
choices.stream().filter((choice) -> choice.getName() != null).collect(Collectors.toMap(Choice::getName,
Function.<Choice>identity());
In my case the logic to get the key is more complex than simply getting a field property, and I would like to avoid doing the logic first in the filter and again in the keyMapper function of Collectors.toMap
How can I convert the list to a map using a custom keyMapper function and filter certain values based on the new key?
choice.getName()
actually an expensive operation? If not, then it seems likely that anything fancier would actually just end up being slower than this straightforward solution.