Issue
I have this piece of code:
private static void computeMapAddition(Map<String, List<XXX>> objectMap,
XXX objectToAdd, String key) {
if (objectMap.containsKey(key)) {
List<XXX> objectList = objectMap
.get(key);
objectList.add(objectToAdd);
} else {
List<XXX> objectList = new ArrayList<>();
objectList.add(objectToAdd);
objectMap.put(key, objectList);
}
}
What this code does:
1) if map contains key then retrieve value - which is List - and add element to that list (it can have lots of elements already)
2) if map doesn't contain a key then create new list, add element to the newly created list and put that (key, value) to the map
Is there any way to make it less verbose using Java 8?
Solution
java 8 added computeIfAbsent
to Map
interface. It does exactly what you want:
// return the list if already present or make a new one, insert into the map
// and return the newly created one
List<XXX> objectList = objectMap.computeIfAbsent(key, k -> new ArrayList<>());
// add new object to list
objectList.add(objectToAdd);
Or you can combine it together as
objectMap.computeIfAbsent(key, k -> new ArrayList<>()).add(objectToAdd);
Answered By - Misha
Answer Checked By - Pedro (JavaFixing Volunteer)