Java8:哈希映射<X,Y>到HashMap<X,Z>使用 S

Java8: HashMaplt;X, Ygt; to HashMaplt;X, Zgt; using Stream / Map-Reduce / Collector(Java8:哈希映射lt;X,Ygt;到HashMaplt;X,Zgt;使用 Stream/Map-Reduce/Collector)
本文介绍了Java8:哈希映射<X,Y>到HashMap<X,Z>使用 Stream/Map-Reduce/Collector的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我知道如何转变";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());

现在我想对地图做基本相同的事情,即:

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
}

解决方案不应仅限于String ->整数.就像上面的 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() 调用中构造新的 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:哈希映射&lt;X,Y&gt;到HashMap&lt;X,Z&gt;使用 Stream/Map-Reduce/Collector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Sending a keyboard event from java to any application (on-screen-keyboard)(将键盘事件从 java 发送到任何应用程序(屏幕键盘))
How to make JComboBox selected item not changed when scrolling through its popuplist using keyboard(使用键盘滚动其弹出列表时如何使 JComboBox 所选项目不更改)
Capturing keystrokes without focus(在没有焦点的情况下捕获击键)
How can I position a layout right above the android on-screen keyboard?(如何将布局放置在 android 屏幕键盘的正上方?)
How to check for key being held down on startup in Java(如何检查在Java中启动时按住的键)
Android - Get keyboard key press(Android - 获取键盘按键)