使用 Java 8 Lambda 表达式将 String 数组转换为 Map [英] Convert String array to Map using Java 8 Lambda expressions
问题描述
是否有更好的函数方式使用 Java 8 lambda 语法将key:value"形式的字符串数组转换为 Map
?
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?
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])));
推荐答案
您可以修改您的解决方案以将 String
数组的 Stream
收集到 Map
(而不是使用 forEach
):
You can modify your solution to collect the Stream
of String
arrays into a Map
(instead of using 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])));
这仍然不能保护您免受所有无效输入的侵害(例如,"c:3r"
会导致 parseDouble
抛出 NumberFormatException
>).
This still doesn't protect you against all invalid inputs (for example "c:3r"
would cause NumberFormatException
to be thrown by parseDouble
).
这篇关于使用 Java 8 Lambda 表达式将 String 数组转换为 Map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!