Suneel Suneel - 4 days ago 4
Java Question

how to remove nested entry in a nested map using dot notation

I have a nested map, something like this:

map.get("employee").get("address").remove("city")


Is there a way to remove the city entry using a key like "employee.address.city"? So I am looking for something like
MapUtil.remove(map,"employee.address.city")

Answer

Not natively, no, though you could write yourself a method to parse your extended map key using String.split("\\."), like this:

public void nestedRemove(Map map, String keyToRemove)
{
    String string = "employee.address.city";
    String[] keys = string.split("\\.");
    Map subMap = null;
    for(int i = 0; i < keys.length -1; i++)
    {
        subMap = subMap.get(keys[i]);
    }
    subMap.remove(keys[i]);
}