Reputation: 21
List<LineOfBusiness> lobArray = new ArrayList<>();
Map<String,String> params = new LinkedHashMap<>();
List<String> scoreValues = Stream.of(StandardizedScore.values())
.filter(o -> !o.getExpectedAction().trim().isEmpty())
.map(o -> String.format("%s,%s,%s", o.getClaimScore(), o.getNetworkScore(), o.getExpectedAction()))
.collect(Collectors.toList());
for (LineOfBusiness lob : LineOfBusiness.values()) {
lobArray.add(lob);
}
for (int i = 0; i < lobArray.size(); i++){
for (int j = 0; j < scoreValues.size(); j++) {
System.out.println(params.put(lobArray.get(i).toString(), scoreValues.get(j)));
}
}
When I try and populate the HashMap
with params.put(lobArray.get(i), scoreValues.get(j))
the keys return as null. The List is definitely populated as values print correctly when I print them in the loop using System.out.println(lobArray.get(i));
. I've tried to debug the code and it picks up the values from the list then too.
Something is going wrong when I add the lobArray
values as the key into the HashMap
. If anyone could spot what is going wrong I'd be very grateful.
Upvotes: 0
Views: 49
Reputation: 1405
You are inserting the values correctly into your map. It's just a matter of printing. You should print the content of your map only after you have inserted your values into the map.
Here's what I mean:
for (int i = 0; i < lobArray.size(); i++){
for (int j = 0; j < scoreValues.size(); j++) {
params.put(lobArray.get(i).toString(), scoreValues.get(j));
}
}
System.out.println(params);
Or, if you want to iterate through the map entries, use entrySet
, and do it like this:
for (Map.Entry<String, String> param : params.entrySet()) {
System.out.println(param);
}
Now, the reason you get null
in your code. According to Map
javadoc, the put
method returns:
the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key, if the implementation supports null values.)
You didn't have any value associated for your key before, that's why the null
is printed.
Upvotes: 3