112. Removal from a Map

Removal from a Map can be accomplished by a key, or by a key and value.

For example, let's assume that we have the following Map:

Map<Integer, String> map = new HashMap<>();
map.put(1, "postgresql");
map.put(2, "mysql");
map.put(3, "derby");

Removal by key is as simple as calling the V Map.remove(Object key) method. If the entry corresponding to the given key is successfully removed, then this method returns the associated value, otherwise it returns null.

Check the following examples:

String r1 = map.remove(1); // postgresql
String r2 = map.remove(4); // null

Now, the map contains the following entries (the entry from key 1 was removed):

2=mysql, 3=derby

Starting with JDK 8, the Map interface was enriched with a new remove() flag method with the following signature: boolean remove​(Object key, Object value). Using this method, we can remove an entry from a map only if there is a perfect match between the given key and value. Basically, this method is a shortcut of the following compound condition: map.containsKey(key) && Objects.equals(map.get(key), value).

Let's have two simple examples:

// true
boolean r1 = map.remove(2, "mysql");

// false (the key is present, but the values don't match)
boolean r2 = map.remove(3, "mysql");

The resultant map contains the single remaining entry, 3=derby.

Iterating and removing from a Map can be accomplished in at least two ways; first, via an Iterator (solution present in the bundled code), and second, starting with JDK 8, we can do it via removeIf​(Predicate<? super E> filter):

map.entrySet().removeIf(e -> e.getValue().equals("mysql"));

More details about removing from a collection are available in the Removing all elements of a collection that match a predicate section.

..................Content has been hidden....................

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