Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map values in a map in Java 8? [duplicate]

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.

like image 638
siledh Avatar asked Apr 22 '14 08:04

siledh


People also ask

Can map have duplicate values in Java?

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.

Can map have multiple values for same key?

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.

How do I allow duplicate keys on a map?

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!


1 Answers

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())); 
like image 176
assylias Avatar answered Sep 19 '22 18:09

assylias