java array to map,使用Java 8 Lambda表达式将字符串数组转换为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 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) :

Map 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 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).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值