Collect stream into a HashMap with Lambda in Java 8
Seems that Collectors.toMap
does not pick up the type arguments of stream.collect
in your example and only returns a Map<Object,Object>
.
As a workaround you can create the result map yourself and in the last stream step add the filtered entries to the result map:
Map<Set<Integer>, Double> result = new HashMap<>();
container.entrySet()
.stream()
.filter(entry -> entry.getKey().size() == size)
.forEach(entry -> result.put(entry.getKey(), entry.getValue()));
If your ending map has a chance of "duplicate keys", there is a better solution using
toMap(Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper,
BinaryOperator<U> mergeFunction,
Supplier<M> mapSupplier)
You could use it like this:
HashMap<Set<Integer>, Double> map = container.entrySet()
.stream()
.filter(k -> k.getKey().size() == size)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (prev, next) -> next, HashMap::new));
Then as duplicate keys are added, it will use the latest instead of throwing an exception. The last parameter is optional.
If you want to keep duplicate keys into a list, then use Collectors.groupingBy
instead.