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

alexgbelov

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.

Joe C

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Convert stream of map to HashMap in Java

How to convert Array to HashMap using Java 8 Stream

How to convert List to Map with indexes using stream - Java 8?

How to convert Array to HashMap in Java with Stream API

Java 8 Convert a stream of set to Map

java 8 stream convert complex map

Java 8 stream: how to Convert Map<String, List<Integer>> to Map<Integer, List<String>> using groupingBy(.)

Java8: How to Convert Map<X, List<Y>> to Map<Y,X> using Stream?

Java 8 stream map custom function and convert it to Map

Java Stream API: how to convert to a Map of Sets

How to convert List<AnyClassObject> to List<Map<String, String>> using Stream in java 8?

Java 8 Stream API: how to convert a List to a Map<Long, Set> having repeated keys in the List?

Java 8 | Parallel Stream for a HashMap

How to convert a for iteration with conditions to Java 8 stream

How to convert a Java 8 Stream to an Array?

How to convert a String to a Java 8 Stream of Characters?

How to convert Stream of Characters into a String in Java 8

Java8: HashMap<X, Y> to HashMap<X, Z> using Stream / Map-Reduce / Collector

How to convert nested for loop into Hashmap using java stream

Java8: convert one map to an another using stream

Java 8 - stream convert map's value type

Convert GraphTraversal<Vertex, Map<Object, List>> into Java8 stream

Convert map to specific dto object using stream JAVA 8

Convert list of Object to Map<Key, List<Object>> with java 8 stream

How to filter Hashmap to update the value on the fly using Java 8 stream?

How can I stream a Map of String and Map using java 8?

How to combine Map values from parent Map with java 8 stream

How to convert a list of objects into a map in Java 8?

How to convert Map to List in Java 8