使用 Java 8 Lambda 表达式将 String 数组转换为 Map

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31693781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:26:34  来源:igfitidea点击:

Convert String array to Map using Java 8 Lambda expressions

javalambdafunctional-programmingjava-8java-stream

提问by bsam

Is there a better functional way of converting an array of Strings in the form of "key:value" to a Mapusing the Java 8 lambda syntax?

是否有更好的功能方法将“key:value”形式的字符串数组转换为Map使用 Java 8 lambda 语法的字符串?

Arrays.asList("a:1.0", "b:2.0", "c:3.0")
        .stream()
        .map(elem -> elem.split(":")
        .collect(Collectors.toMap(keyMapper?, valueMapper?));

The solution I have right now does not seem really functional:

我现在的解决方案似乎并没有真正起作用:

Map<String, Double> kvs = new HashMap<>();
Arrays.asList("a:1.0", "b:2.0", "c:3.0")
        .stream()
        .map(elem -> elem.split(":"))
        .forEach(elem -> kvs.put(elem[0], Double.parseDouble(elem[1])));

采纳答案by Eran

You can modify your solution to collect the Streamof Stringarrays into a Map(instead of using forEach) :

您可以修改您的解决方案以将StreamofString数组收集到 a Map(而不是使用forEach)中:

Map<String, Double> kvs =
    Arrays.asList("a:1.0", "b:2.0", "c:3.0")
        .stream()
        .map(elem -> elem.split(":"))
        .collect(Collectors.toMap(e -> e[0], e -> Double.parseDouble(e[1])));

Of course this solution has no protection against invalid input. Perhaps you should add a filter just in case the split String has no separator :

当然,这个解决方案没有针对无效输入的保护。也许您应该添加一个过滤器,以防拆分字符串没有分隔符:

Map<String, Double> kvs =
    Arrays.asList("a:1.0", "b:2.0", "c:3.0")
        .stream()
        .map(elem -> elem.split(":"))
        .filter(elem -> elem.length==2)
        .collect(Collectors.toMap(e -> e[0], e -> Double.parseDouble(e[1])));

This still doesn't protect you against all invalid inputs (for example "c:3r"would cause NumberFormatExceptionto be thrown by parseDouble).

这仍然不能保护您免受所有无效输入的影响(例如"c:3r"会导致NumberFormatException被 抛出parseDouble)。