将列表转换为地图

时间:2016-03-05 10:20:34

标签: java lambda java-8

我有一个我要转换为地图的字符串列表。我尝试了以下但我似乎无法弄清楚为什么它不起作用

List<String> dataList = new ArrayList<>( //code to create the list );

Map<String, Double> doubleMap = dataList.stream().collect(Collectors.toMap(o->o, Double::new));

我得到的是:

java.lang.NumberFormatException: For input string: "Test1"

它似乎试图将一个字符串放入值(这是一个Double),而不是创建一个空/ null double。

我基本上希望地图包含String,每条记录为0.0。

1 个答案:

答案 0 :(得分:6)

您正试图将String传递给public Double(String s)构造函数,如果您的List包含无法解析为String的任何double,则会失败。

Double构造函数的方法引用传递给toMap时,它相当于:

Map<String, Double> doubleMap = dataList.stream().collect(Collectors.toMap(o->o, o->new Double(o)));

相反,写一下:

Map<String, Double> doubleMap = dataList.stream().collect(Collectors.toMap(o->o, o->0.0));
相关问题