September 2019
Intermediate to advanced
816 pages
18h 47m
English
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 ...