0

I've got a hashmap who contains a arraylist as value. I want to check if one of the arraylists contains a object, and then remove that object from the arraylist. But, how?

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

My hashmap:

HashMap<String,ArrayList<UUID>> inareamap = new HashMap<String, ArrayList<UUID>>();

I want 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 (ArrayList<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);
                }
            }
        }
    }
}
stijnb1234
  • 162
  • 2
  • 15
  • the hashmap isn't the problem, You are trying to remove an object for the list while looping threw it. To solve this you have to use iterator.remove see https://stackoverflow.com/questions/223918/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re – user43968 Aug 09 '19 at 13:29
  • Check this too https://www.baeldung.com/java-concurrentmodificationexception – saurav Aug 09 '19 at 13:30
  • @user43968 Thanks for your reply! I've tried using the iterator, but I don't know how to use it in combination with the hashmap. – stijnb1234 Aug 09 '19 at 13:36
  • 1
    Also, I recommend using `List` in place of `ArrayList` when defining the type, program to the interface, not to the implementation. – Marco Marchetti Aug 09 '19 at 13:48

4 Answers4

2

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));
});
cameron1024
  • 7,007
  • 2
  • 11
  • 28
1

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

Dario
  • 73
  • 6
0

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);
    }
}
Torsten Fehre
  • 567
  • 2
  • 7
0

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