简体   繁体   中英

Copying keys from one map to another

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM