r/learnjava • u/WrickyB • Apr 28 '21
TIL of the method computeIfAbsent
While working, I needed a way to "cache" some data and the results of processing said data and return said data. I did something like this:
private String method(String key) {
if (cacheMap.containsKey(key)) {
return cacheMap.get(key);
} else {
var res = calc(key);
cacheMap.put(key, res);
return res;
}
}
I was looking through the docs when I discovered this:
public default V computeIfAbsent(K, java.util.function.Function<? super K, ? extends V>);
With it, my code became significantly cleaner:
private String method(String key) {
return cacheMap.computeIfAbsent(key, this::calc);
}
I found this to be really helpful and I wanted to share it. Enjoy
81
Upvotes
11
u/HecknChonker Apr 29 '21 edited Apr 29 '21
There is also compute(key, function) and computeIfPresent(key, function)
I actually learned about these methods because IntelliJ has an auto-inspection that replaces this:
with this:
Another really cool method is merge.
Say you are counting words in a book. If the word is not in the map, it will insert it with a value of 1. If it is already in the map it will increment the value by 1.