Java – if value is empty, delete the key

Suppose we have a map < key, collection < value > > mymap and a method to delete values from the collection associated with the key If deleting the value makes the collection empty, we want to delete the key entry in the mapping:

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

Are there any Java 8 methods that implement the described behavior through a single thread or shorter?

Solution

You can use computeifpresent:

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);
}

If the value is not null, computeifpresent applies bifunction to the current value in the key and mapping (if it is null, computeifpresent immediately returns null). If the return value is not null, set the value to the return value of bifunction. If the return value is null, delete the key from the map and finally return a new value

Note that its behavior is slightly different from the method you proposed - it does not delete an empty list from the map because remove will return false If you want to delete an empty list, you can use l.isempty() | (l.remove (value) & & l.isempty())

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>