如何在 Java8中映射映射中的值?

假设我有一个 Map<String, Integer>。有没有一个简单的方法从它得到一个 Map<String, String>

我说的容易,不是指这样:

Map<String, String> mapped = new HashMap<>();
for(String key : originalMap.keySet()) {
mapped.put(key, originalMap.get(key).toString());
}

而是一些类似于:

Map<String, String> mapped = originalMap.mapValues(v -> v.toString());

但显然没有 mapValues方法。

115323 次浏览

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

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:

  1. Obtain a Stream<Map.Entry<String, Integer>>
  2. Collect the results in the resulting map:
    1. Map the entries to their key.
    2. 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.