Map has added two new methods to replace in Java 8
1. replace(k,v)
The specified key will be mapped to the specified value (new value) only when the specified key already exists and there is a mapping value related to it.
When the specified key does not exist, the method returns a null
The javadoc comment explains the equivalent Java code for the implementation of this default value method:
if (map.containsKey(key)) { return map.put(key, value);} else { return null;}The following is a comparison of the new method and the previous method before JDK8:
/* * Demonstrate the Map.replace(K, V) method and compare it with the implementation method before JDK8. The newly added Map.replace(K, V) method in JDK8 * uses fewer lines of code than traditional implementation methods* and allows a final variable to receive the return value. */// Implementation method before JDK8 String replacedCapitalCity; if (statesAndCapitals.containsKey("Alaska")) { replacedCapitalCity = statesAndCapitals.put("Alaska", "Juneau");}// Implementation method of JDK8 final String replacedJdk8City = statesAndCapitals.replace("Alaska", "Juneau");2. replace(k,v,v)
The second newly added Map replace method has a narrower interpretation range in replacing existing values. When that method (the previous replace method) just covers the replacement process of the specified key with any valid value in the map, this "replace" method accepts an additional (third) parameter, which will only be replaced if both the specified key and the value match.
The javadoc comment illustrates the implementation of this default value method:
if (map.containsKey(key) && Objects.equals(map.get(key), value)) { map.put(key, newValue); return true;} else { return false;}The following code list shows a specific comparison between the new implementation method and the implementation method before JDK8.
/* * Demonstrate the Map.replace(K, V, V) method and compare it with the implementation method before JDK8. The newly added Map.replace(K, V, V) method in JDK8 * uses fewer lines of code than traditional implementation methods* and allows a final variable to receive the return value. */// Implementation method before JDK8 boolean replaced = false; if ( statesAndCapitals.containsKey("Nevada") && Objects.equals(statesAndCapitals.get("Nevada"), "Las Vegas")) { statesAndCapitals.put("Nevada", "Carson City"); replaced = true; }// Implementation method of JDK8 final boolean replacedJdk8 = statesAndCapitals.replace("Nevada", "Las Vegas", "Carson City");The above is the brief discussion of the new method of map in Java 8 - replace - all contents of replace. I hope everyone will support Wulin.com~