How to convert a stream to a HashMap (not Map) in Java 8
hashmap, java, java-8, java-stream
Solution
One of the overloads to the `Collectors.toMap` method will allow you to select a map implementation of your choice.
Unfortunately, one of the drawbacks to this overload is that it also requires a method to merge two values when they have the same key (though I often reference a method that always throws in that case).
HashMap<K, V> myHashMap = listToTransform.stream().map(/* do my transformation here */)
.collect(Item::getKey, Item::getValue, this::throwIllegalArgumentException, HashMap::new);
Problem
I have a stream, and I want to explicitly collect it into a HashMap. Right now, I'm doing something like ``` List<Item> listToTransform = //initialized and populated HashMap<K, V> myHashMap = new HashMap<>(); listToTransform.stream().map(/* do my transformation here */) .forEach(i -> myHashMap.put(i.getKey(), i.getValue())); ``` I was wondering if there was a way of using Collectors to explicitly get back a HashMap.