Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8: convert one map to another map using stream

Tags:

I need to convert a Java HashMap to an instance of TreeMap (including map contents)

HashMap<String, Object> src = ...; TreeMap<String, Object> dest = src.entrySet().stream()         .filter( ... )         .collect(Collectors.toMap( ???, ???, ???, TreeMap::new)); 

What should I put in place of ??? to make this code compilable?

like image 590
Antonio Avatar asked Sep 07 '14 16:09

Antonio


People also ask

How will you convert a list into map using streams in Java 8?

With Java 8, you can convert a List to Map in one line using the stream() and Collectors. toMap() utility methods. The Collectors. toMap() method collects a stream as a Map and uses its arguments to decide what key/value to use.

Can we use Stream on map?

Converting only the Value of the Map<Key, Value> into Stream: This can be done with the help of Map. values() method which returns a Set view of the values contained in this map. In Java 8, this returned set can be easily converted into a Stream of key-value pairs using Set. stream() method.

Can we modify map while iterating?

It is not allowed to modify a map in Java while iterating over it to avoid non-deterministic behavior at a later stage.

How do you collect a Stream map?

Method 1: Using Collectors.toMap() Function The Collectors. toMap() method takes two parameters as the input: KeyMapper: This function is used for extracting keys of the Map from stream value. ValueMapper: This function used for extracting the values of the map for the given key.


1 Answers

From Collectors.toMap(...) javadoc:

 * @param keyMapper a mapping function to produce keys  * @param valueMapper a mapping function to produce values  * @param mergeFunction a merge function, used to resolve collisions between  *                      values associated with the same key, as supplied  *                      to {@link Map#merge(Object, Object, BiFunction)}  * @param mapSupplier a function which returns a new, empty {@code Map} into  *                    which the results will be inserted 

For example:

HashMap<String, Object> src = ...; TreeMap<String, Object> dest = src.entrySet().stream()       .filter( ... )       .collect(Collectors.toMap(Map.Entry::getKey , Map.Entry::getValue, (a,b) -> a, TreeMap::new)); 
like image 189
NiematojakTomasz Avatar answered Oct 05 '22 23:10

NiematojakTomasz