Java8:HashMap< X,Y>到HashMap< X,Z>使用Stream / Map-Reduce / Collector [英] Java8: HashMap<X, Y> to HashMap<X, Z> using Stream / Map-Reduce / Collector

查看:132
本文介绍了Java8:HashMap< X,Y>到HashMap< X,Z>使用Stream / Map-Reduce / Collector的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何从 Y - > 转换一个简单的Java List Z ,即:

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

现在我想用Map做基本相同的事情,即:

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
}

解决方案不应限于字符串 - > 整数。就像上面的 List 示例一样,我想调用任何方法(或构造函数)。

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).

推荐答案

Map<String, String> x;
Map<String, Integer> y =
    x.entrySet().stream()
        .collect(Collectors.toMap(
            e -> e.getKey(),
            e -> Integer.parseInt(e.getValue())
        ));

它不如列表代码好。你不能在地图中构造新的 Map.Entry ()调用以便将工作混合到 collect()调用中。

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.

这篇关于Java8:HashMap&lt; X,Y&gt;到HashMap&lt; X,Z&gt;使用Stream / Map-Reduce / Collector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆