1

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);
                }
            }
        }
    }
}
stijnb1234
  • 184
  • 4
  • 19
  • 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
  • 9,083
  • 2
  • 16
  • 36
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();
        }
    }