Home > front end >  Kotlin - Remove element in the set while iterating
Kotlin - Remove element in the set while iterating

Time:03-31

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

CodePudding user response:

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

CodePudding user response:

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.)

  • Related