使用Java 8 Lambda表达式将字符串数组转换为Map [英] Convert String array to Map using Java 8 Lambda expressions
问题描述
使用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?));
我现在所拥有的解决方案似乎并不实用:
Map< String,Double> kvs = new HashMap<>;
Arrays.asList(a:1.0,b:2.0,c:3.0)
(elem - > elem.split(:))
.forEach(elem - > kvs.put(elem [0],Double.parseDouble(elem [ 1])));
解决方案将
String
数组的Stream
收集到Map
(而不是使用forEach
):
映射< String,D ouble> 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]));
当然,这个解决方案对于无效输入没有保护作用,也许你应该添加一个过滤器,以防分割字符串没有分隔符:
映射< 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会导致 NumberFormatException
由parseDouble
)引发。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])));
解决方案You can modify your solution to collect the
Stream
ofString
arrays into aMap
(instead of usingforEach
) :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 causeNumberFormatException
to be thrown byparseDouble
).这篇关于使用Java 8 Lambda表达式将字符串数组转换为Map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!