简体   繁体   English

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

[英]Convert String array to Map using Java 8 Lambda expressions

Is there a better functional way of converting an array of Strings in the form of "key:value" to a Map using the Java 8 lambda syntax?是否有更好的功能方式使用 Java 8 lambda 语法将“key:value”形式的字符串数组转换为Map

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

You can modify your solution to collect the Stream of String arrays into a Map (instead of using forEach ) :您可以修改您的解决方案以将String数组Stream收集到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 NumberFormatException to be thrown by parseDouble ).这仍然不能保护您免受所有无效输入的影响(例如, "c:3r"会导致parseDouble抛出NumberFormatException )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM