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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access