How to convert stream to HashMap (not Map) in Java 8

I have a stream and I want to explicitly collect it in a HashMap. Right now, I am 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 is a way to use Collectors to return a HashMap explicitly.

+3


source to share


1 answer


One of the method overloads Collectors.toMap

will allow you to choose the map implementation of your choice.

Unfortunately, one of the downsides to this overload is that it also requires a method to combine two values ​​when they have the same key (although I often refer to a method that always throws in this case).



HashMap<K, V> myHashMap = listToTransform.stream().map(/* do my transformation here */)
.collect(Item::getKey, Item::getValue, this::throwIllegalArgumentException, HashMap::new);

      

+6


source







All Articles