alexgbelov
alexgbelov

Reputation: 3121

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

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.

Upvotes: 3

Views: 4093

Answers (1)

Joe C
Joe C

Reputation: 15684

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);

Upvotes: 6

Related Questions