110. Mapping a default value

Before JDK 8, the solution to this problem relied on a helper method, which basically checks the presence of the given key in a Map and returns the corresponding value, or a default value. Such a method can be written in a utility class or by extending the Map interface. By returning a default value, we avoid returning null if the given key was not found in the Map. Moreover, this is a convenient approach for relying on a default setting or configuration.

Starting with JDK 8, the solution to this problem consists of a simple invocation of the Map.getOrDefault() method. This method gets two arguments representing the key to look up in the Map method and the default value. The default value acts as the backup value that should be returned when the given key is not found.

For example, let's assume the following Map that wraps several databases and their default host:port:

Map<String, String> map = new HashMap<>();
map.put("postgresql", "127.0.0.1:5432");
map.put("mysql", "192.168.0.50:3306");
map.put("cassandra", "192.168.1.5:9042");

And, let's try to see whether this Map contains the default host:port for Derby DB as well:

map.get("derby"); // null

Since Derby DB is not present in the map, the result will be null. This is not what we want. Actually, when the searched database is not present on the map, we can use MongoDB on 69:89.31.226:27017, which is always available. Now, we can easily shape this behavior as follows:

// 69:89.31.226:27017
String hp1 = map.getOrDefault("derby", "69:89.31.226:27017");

// 192.168.0.50:3306
String hp2 = map.getOrDefault("mysql", "69:89.31.226:27017");
This method is convenient for building fluent expressions and avoiding disrupting the code for null checks. Note that returning the default value doesn't mean that this value will be added to the Map. Map remains unmodified.
..................Content has been hidden....................

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