Skip to content

Instantly share code, notes, and snippets.

@adam-hurwitz
Last active January 11, 2021 20:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adam-hurwitz/34433c37046dae2a0a613d291a5efc56 to your computer and use it in GitHub Desktop.
Save adam-hurwitz/34433c37046dae2a0a613d291a5efc56 to your computer and use it in GitHub Desktop.
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