Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 857
Aeseir Avatar asked Apr 09 '26 03:04

Aeseir


1 Answers

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));
like image 86
Eran Avatar answered Apr 11 '26 19:04

Eran