'Remove element in the set while iterating

I have the following scenario: In the details variable, I need to remove a course from the mutable set of courses, for each student based on a condition.

If I remove as I have done below, I get concurrent modification exception, because I am modifying the variable while iterating through it.

How can I iterate the map in reverse so that it doesn't throw the deadlock, or is there a better way to handle this scenario ?

val details = MutableMap<Student, MutableSet<CourseDetail>>

details?.forEach { student, courses ->
    courses?.forEach { course ->
       if (b?.contains(course) == false) {
           details[student]?.remove(course)
    }
  }
}


Solution 1:[1]

It sounds like you just want

for (courses in details.values) {
  courses.retainAll(b)
}

(Notably, you should also avoid null collections so you don't have to scatter ?. everywhere.)

Solution 2:[2]

You can use ConcurrentHashMap and ConcurrentHashSet it provide thread safety or

simply use iterator to remove element while iterating

details?.forEach { student, courses ->
    Iterator<CourseDetail> itr = courses.iterator();
    while (itr.hasNext())
        if (b?.contains(itr.next()) == false) itr.remove();
 }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Louis Wasserman
Solution 2 Abhishek Bansal