javaarraylisthashmapkeyset

Remove a value from a List nested in a Map


I've got a HashMap which contains an ArrayList as value. I want to check if one of the lists contains an object and remove that object from the list. How can I achieve that?

I've tried using some for loops, but then I get a ConcurrentModificationException. I can't get that exception away.

My hashmap:

Map<String,List<UUID>> inAreaMap = new HashMap<String, ArrayList<UUID>>();

I intend to check if the ArrayList contains the UUID I've got, and if so, I want to remove it from that ArrayList. But I don't know the String at that position of the code.

What I already tried:

for (List<UUID> uuidlist : inAreaMap.values()) {
    for (UUID uuid : uuidlist) {
        if (uuid.equals(e.getPlayer().getUniqueId())) {
            for (String row : inAreaMap.keySet()) {
                if (inAreaMap.get(row).equals(uuidlist)) {
                    inAreaMap.get(row).remove(uuid);
                }
            }
        }
    }
}

Solution

  • There is a more elegant way to do this, using Java 8:

    Map<String, ArrayList<UUID>> map = ...
    UUID testId = ...
    // defined elsewhere
    
    // iterate through the set of elements in the map, produce a string and list for each
    map.forEach((string, list) -> { 
    
        // as the name suggests, removes if the UUID equals the test UUID
        list.removeIf(uuid -> uuid.equals(testId));
    });