Remove a value from a List nested in a Map

2.9k views Asked by At

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

There are 4 answers

0
cameron1024 On BEST ANSWER

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));
});
1
Dario On

try with the iterator. inareamap.iterator().. and.. iterator.remove()

0
Torsten Fehre On

If you have Java 8, the solution of camaron1024's solution is the best. Otherwise you can make use of the fact that you have a list and iterate through it backwards by index.

for(ArrayList<UUID> uuidlist : inareamap.values()) {
    for(int i=uuidlist.size()-1;i>=0;i--) {
        if (uuidlist.get(i).equals(e.getPlayer().getUniqueId()))
            uuidlist.remove(i);
    }
}
0
zero__code On

Here the easy solution.

    UUID key = ... ;
    for(Map.Entry<String,ArrayList<UUID>> e : hm.entrySet()){
        Iterator<UUID> itr = e.getValue().iterator();
        while(itr.hasNext()){
            if(itr.next() == key)
                itr.remove();
        }
    }