I have two maps. One with default values of 0 and one with set values. For example
Map<String,Integer> defaultTaskScores = new HashMap<String, Integer>(){{
put("Phalanxing", 0);
put("Shieldwalling",0);
put("Tercioing",0);
put("Wedging",0);
}};
Map<String,Integer> taskScores = new HashMap<String, Integer>(){{
put("Phalanxing", 90);
put("Shieldwalling",56);
put("Wedging",24);
}};
I want to put into taskScores a pair of key-value from defaultTaskScores which key's isn't in taskScores. For this example it's putting Tercioing with value of 0.
taskScores maps are in the list
List<CourseResult> courseResultList;
public class CourseResult {
private final Person person;
private final Map<String, Integer> taskResults;
public CourseResult(final Person person, final Map<String, Integer> taskResults) {
this.person = person;
this.taskResults = taskResults;
}
}
CodePudding user response:
You could iterate over defaultTaskScores
and use putIfAbsent
to add the missing keys to taskScores
:
defaultTaskScores.keySet().forEach(k -> taskScores.putIfAbsent(k, 0));
EDIT:
An alternate approach could be to apply the default value when retrieving a score from the map. Instead of calling taskScaores.get(someKey)
, you could use taskScores.getOrDefault(someKey, 0)
.
CodePudding user response:
Only put in the Map those values if the key is not already there:
for(Map.Entry<String, Integer> entry : defaultTaskScores.entrySet()) {
taskScores.putIfAbsent( entry.getKey(), entry.getValue() );
}
CodePudding user response:
You can create iterate over the entries of defaultTaskScores
with enhanced for
-loop using entry set as a source, or by invoking forEach()
method on thedefaultTaskScores
map directly.
To update taskScores
you can use Java 8 methods:
defaultTaskScores.forEach(taskScores::putIfAbsent);
defaultTaskScores.forEach((k, v) -> taskScores.computeIfAbsent(k, (key) -> v));
In case if you're not comfortable with lambda expressions and method references, have a look at this tutorial created by Oracle.
Sidenote: avoid using obsolete double brace initialization, it creates an anonymous class under the hood and might cause memory leaks. Since Java 9 we have a family of overloaded factory methods Map.of()
and method Map.ofEntries()
which produce an immutable map. When you need a map which is mutable like in this case, you can wrap it with a HashMap
, like that:
Map<String, Integer> taskScores = new HashMap<>(Map.of(
"Phalanxing", 90, "Shieldwalling",56,"Wedging",24
));