I have a map for which the values are a collection. Given a key, I want to remove an element of the collection and return it, but I also want to remove the entry if the collection is empty. Is there a way to do this in a short way using one of the numerous new Map methods of Java 8?
One easy example (I use a Stack but it could be a List, a Set, etc.). For the sake of the example, let's say that it is already checked that the map contains the key.
public static String removeOne(Map<Integer, Stack<String>> map, int key) {
Stack<String> stack = map.get(key);
String result = stack.pop();
if(stack.isEmpty()){
map.remove(key);
}
return result;
}
I tried doing something like
map.compute(1, (k, v) -> {v.pop(); return v.size() == 0 ? null : v;});
But even though it does indeed remove the entry if empty, I don't know how to get the value returned by pop().