Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ODG - Kotlin: Avoiding ConcurrentModificationException
val integers = arrayListOf(1, 2, 3)
// Filter using streams.
val newIntegers = integers.filter { it != 2 }
// Use removeIf()
integers.removeIf { it == 2 }
// Use an iterator directly.
val iterator = integers.iterator()
while (iterator.hasNext()) {
val integer = iterator.next()
if (integer == 2) {
iterator.remove()
}
}
// Remove after iteration.
val toRemove = arrayListOf<Int>()
for (i in integers) {
if (i == 2) {
toRemove.add(i)
}
}
integers.removeAll(toRemove)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment