How to map values in a map in Java 8? [duplicate]
The easiest way to do so is:
Map<String, Integer> map = new HashMap<>();Map<String, String> mapped = map.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, entry -> String.valueOf(entry.getValue())));
What you do here, is:
- Obtain a
Stream<Map.Entry<String, Integer>>
- Collect the results in the resulting map:
- Map the entries to their key.
- Map the entries to the new values, incorporating
String.valueOf
.
The reason you cannot do it in a one-liner, is because the Map
interface does not offer such, the closest you can get to that is map.replaceAll
, but that method dictates that the type should remain the same.