Converting a List to Map

2019-05-10 08:15发布

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));

All i get is:

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

It seems to be trying to put a string into the value (which is a Double) instead of creating an empty/null double.

I essentially want the map to contain the String, 0.0 for each record.

1条回答
你好瞎i
2楼-- · 2019-05-10 09:14

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.

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)));

Instead, write :

Map<String, Double> doubleMap = dataList.stream().collect(Collectors.toMap(o->o, o->0.0));
查看更多
登录 后发表回答