On the new method of map in java8 replace

  • 2020-05-10 18:09:10
  • OfStack

Map has added two replace methods to Java8

1.replace(k,v)

The specified key is mapped to the specified value (the new value) only when the specified key already exists and has a mapping value associated with it

If the specified key does not exist, the method return returns 1 null

The javadoc comments explain the equivalent Java code for the implementation of the default method:


if (map.containsKey(key)) {
  return map.put(key, value);
} else {
  return null;
}

Here's how the new method compares to the one before JDK8:


/*
 *  demonstration Map.replace(K, V) Methods and JDK8 Compare previous implementations. JDK8
 *  In the new Map.replace(K, V) Methods use fewer lines of code than traditional implementations 
 *  And allow the use of 1 a final A variable of type to receive the return value.  
 */

// JDK8 The previous implementation 
String replacedCapitalCity;
if (statesAndCapitals.containsKey("Alaska")) {
  replacedCapitalCity = statesAndCapitals.put("Alaska", "Juneau");
}

// JDK8 Implementation mode 
final String replacedJdk8City = statesAndCapitals.replace("Alaska", "Juneau");

2.replace(k,v,v)

The second new Map replace method has a narrower definition range in replacing existing values. When that method (the last replace method) only covers the substitution of the specified key with any one valid value in the mapping, the "replace" method accepts an additional (third) parameter and will only be substituted if the specified key and value match.

The javadoc annotation explains the implementation of the default method:


if (map.containsKey(key) && Objects.equals(map.get(key), value)) {
  map.put(key, newValue);
  return true;
} else {
  return false;
}

The following code illustrates a specific comparison between the new implementation and the one before JDK8.


/*
 *  demonstration Map.replace(K, V, V) Methods and JDK8 Compare previous implementations. JDK8
 *  In the new Map.replace(K, V, V) Methods use fewer lines of code than traditional implementations 
 *  And allow the use of 1 a final A variable of type to receive the return value.  
 */

// JDK8 The previous implementation 
 boolean replaced = false;
 if (  statesAndCapitals.containsKey("Nevada")
  && Objects.equals(statesAndCapitals.get("Nevada"), "Las Vegas")) {
   statesAndCapitals.put("Nevada", "Carson City");
   replaced = true;
 }

// JDK8 Implementation mode 
final boolean replacedJdk8 = statesAndCapitals.replace("Nevada", "Las Vegas", "Carson City");

Related articles: