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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With