Java8: HashMap<X, Y> to HashMap<X, Z> using Stream / Map-Reduce / Collector

Benjamin M picture Benjamin M · Sep 18, 2014 · Viewed 181k times · Source

I know how to "transform" a simple Java List from Y -> Z, i.e.:

List<String> x;
List<Integer> y = x.stream()
        .map(s -> Integer.parseInt(s))
        .collect(Collectors.toList());

Now I'd like to do basically the same with a Map, i.e.:

INPUT:
{
  "key1" -> "41",    // "41" and "42"
  "key2" -> "42      // are Strings
}

OUTPUT:
{
  "key1" -> 41,      // 41 and 42
  "key2" -> 42       // are Integers
}

The solution should not be limited to String -> Integer. Just like in the List example above, I'd like to call any method (or constructor).

Answer

John Kugelman picture John Kugelman · Sep 18, 2014
Map<String, String> x;
Map<String, Integer> y =
    x.entrySet().stream()
        .collect(Collectors.toMap(
            e -> e.getKey(),
            e -> Integer.parseInt(e.getValue())
        ));

It's not quite as nice as the list code. You can't construct new Map.Entrys in a map() call so the work is mixed into the collect() call.