Java Reference
In-Depth Information
checks whether a Map contains a mapping for a given key. If not, you can provide a default value
to return instead. Previously you would do this:
Map<String, Integer> carInventory = new HashMap<>();
Integer count = 0;
if(map.containsKey("Aston Martin")){
count = map.get("Aston Martin");
}
You can now more simply do the following:
Integer count = map.getOrDefault("Aston Martin", 0);
Note that this works only if there's no mapping. For example, if the key is explicitly mapped to
the value null, then no default value will be returned.
Another particularly useful method is computeIfAbsent, which we briefly mentioned in
chapter
14
when explaining memoization. It lets you conveniently use the caching pattern. Let's say that
you need to fetch and process data from different websites. In such a scenario, it's useful to
cache the data, so you don't have to execute the (expensive) fetching operation multiple times:
You can now write this code more concisely by using computeIfAbsent as follows:
public String getData(String url){
return cache.computeIfAbsent(url, this::getData);
}
that ConcurrentHashMap was also updated with additional methods. We discuss them in
Search WWH ::
Custom Search