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?
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.
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.
It is not allowed to modify a map in Java while iterating over it to avoid non-deterministic behavior at a later stage.
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With