Java Tip: ComputeIfAbsent
Often we have to loop through a list of items and convert it into a map, with the key being some sort of category and the value being a set of the associated items ie Map<Key, Set<Object>>
. The old way of doing this looped through the list and before adding checked if the key was present. Using computeIfAbsent we can clean up this syntax considerably.
Instead of
// Map of item types to items
Map<String, Set<Items>> map = new HashMap<>();
for (Item item: items) {
if (map.containsKey(item.getType())) {
map.get(item.getType().add(item));
} else {
Set newSet = new HashSet<>();
newSet.add(item);
map.put(item.getType(), newSet));
}
}
Do
// Map of item types to items
Map<String, Set<Items>> map = new HashMap<>();
for (Item item: items) {
map.computeIfAbsent(item.getType(), v -> new HashSet<>()).
add(item);
}