r/learnjava • • 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

2 comments sorted by

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:

    var map = new HashMap<String, List<String>>();
    var list = map.get(key);
    if (list == null) {
        list = new ArrayList<>();
        map.put(key, list);
    }

with this:

var map = new HashMap<String, List<String>>();
var list = map.computeIfAbsent(key, k -> new ArrayList<>());

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.

var map = new HashMap<String, Long>();
map.merge(key, 1L, Long::sum);

2

u/Puzzleheaded-Order84 Apr 29 '21

For your second example you can do it with a nested get or default but I’m not sure what is better