Say I have a Map<String, Integer>
. Is there an easy way to get a Map<String, String>
from it?
By easy, I mean not like this:
Map<String, String> mapped = new HashMap<>(); for(String key : originalMap.keySet()) { mapped.put(key, originalMap.get(key).toString()); }
But rather some one liner like:
Map<String, String> mapped = originalMap.mapValues(v -> v.toString());
But obviously there is no method mapValues
.
Map does not supports duplicate keys. you can use collection as value against same key. Because if the map previously contained a mapping for the key, the old value is replaced by the specified value.
The Map interface stores the elements as key-value pairs. It does not allow duplicate keys but allows duplicate values. HashMap and LinkedHashMap classes are the widely used implementations of the Map interface. But the limitation of the Map interface is that multiple values cannot be stored against a single key.
You can use a TreeMap with a custom Comparator in order to treat each key as unequal to the others. It would also preserve the insertion order in your map, just like a LinkedHashMap. So, the net result would be like a LinkedHashMap which allows duplicate keys!
You need to stream the entries and collect them in a new map:
Map<String, String> result = map.entrySet() .stream() .collect(Collectors.toMap(Entry::getKey, e -> String.valueOf(e.getValue()));
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