113. Replacing entries from a Map

Replacing entries from a Map is a problem that can be encountered in a wide range of cases. The convenient solution to accomplish this and avoid a snippet of spaghetti code written in a helper method relies on JDK 8, the replace() method.

Let's assume that we have the following Melon class and a map of Melon:

public class Melon {

private final String type;
private final int weight;

// constructor, getters, equals(), hashCode(),
// toString() omitted for brevity
}

Map<Integer, Melon> mapOfMelon = new HashMap<>();
mapOfMelon.put(1, new Melon("Apollo", 3000));
mapOfMelon.put(2, new Melon("Jade Dew", 3500));
mapOfMelon.put(3, new Melon("Cantaloupe", 1500));

Replacing the melon corresponding to key 2 can be accomplished by means of V replace​(K key, V value). If the replacement is successful, then this method will return the initial Melon:

// Jade Dew(3500g) was replaced
Melon melon = mapOfMelon.replace(2, new Melon("Gac", 1000));

Now, the map contains the following entries:

1=Apollo(3000g), 2=Gac(1000g), 3=Cantaloupe(1500g)

Furthermore, let's suppose that we want to replace the entry with key 1 and the Apollo melon (3,000g). So, the melon should be the same one in order to obtain a successful replacement. This can be accomplished via the Boolean, replace​(K key, V oldValue, V newValue). This method relies on the equals() contract to compare the given values; therefore Melon needs to implement the equals() method, otherwise the result will be unpredictable:

// true
boolean melon = mapOfMelon.replace(
1, new Melon("Apollo", 3000), new Melon("Bitter", 4300));

Now, the map contains the following entries:

1=Bitter(4300g), 2=Gac(1000g), 3=Cantaloupe(1500g)

Finally, let's assume that we want to replace all entries from a Map based on a given function. This can be done via void replaceAll​(BiFunction<? super K,​? super V,​? extends V> function).

For example, let's replace all melons that weigh more than 1,000 g with melons weighing equal to 1,000g. The following BiFunction shapes this function (k is the key and v is the value of each entry from the Map):

BiFunction<Integer, Melon, Melon> function = (k, v) 
-> v.getWeight() > 1000 ? new Melon(v.getType(), 1000) : v;

Next, replaceAll() appears on the scene:

mapOfMelon.replaceAll(function);

Now, the map contains the following entries:

1=Bitter(1000g), 2=Gac(1000g), 3=Cantaloupe(1000g)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset