将列表转换为映射 [英] Converting a List to Map
问题描述
我有一个我要转换为地图的字符串列表。我尝试了以下但我似乎无法弄清楚为什么它不起作用
I got a list of Strings that i want to convert to a map. I tried the below but i can't seem to figure out why its not working
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。
It seems to be trying to put a string into the value (which is a Double) instead of creating an empty/null double.
我基本上希望地图包含字符串,每条记录0.0。
I essentially want the map to contain the String, 0.0 for each record.
推荐答案
您正在尝试传递字符串
到 public Double(String s)
构造函数,如果 List
包含任何 String
无法解析为 double
。
You are trying to pass a String
to the public Double(String s)
constructor, which fails if your List
contains any String
that cannot be parsed as a double
.
当您将 Double
构造函数的方法引用传递给 toMap $ c时$ c>,相当于:
When you pass a method reference of a Double
constructor to toMap
, it's equivalent to :
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));
这篇关于将列表转换为映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!