How to map values in a map in Java 8?

siledh picture siledh · Apr 22, 2014 · Viewed 74.1k times · Source

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.

Answer

assylias picture assylias · Apr 22, 2014

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