dabadaba dabadaba - 5 months ago 10x
Java Question

Remove key if value is absent

Say we have a

Map<Key, Collection<Value>> myMap
and a method that removes a value from the collection associated to a key. If removing a value leaves the collection empty, we'd want to get rid of the
entry in the map:

List<Value> removeValue(Key key, Value value) {
List<Value> v = myMap.get(key);
if (v != null) {
if (v.isEmpty())
return v;

Is there any Java 8 way to achieve the described behavior with a one-liner or shorter method?


You can use computeIfPresent for this:

static <K, V> List<V> removeValue(K key, V value, Map<K, List<V>> map){
    return map.computeIfPresent(key, (k, l) -> l.remove(value) && l.isEmpty() ? null : l);

computeIfPresent applies the BiFunction to the key and the current value in the map if the value is not null (if it is null computeIfPresent returns null immediately) and then either sets the value to the return value of the BiFunction if the return value is not null or removes the key from the map if the return value is null and finally returns the new value.

Note that it behaves slightly differently to the method in you question - it will not remove an already empty List from the map because remove will return false. If you want to remove an already empty List you could use l.isEmpty() || (l.remove(value) && l.isEmpty()).