Last active
January 11, 2021 20:43
-
-
Save adam-hurwitz/34433c37046dae2a0a613d291a5efc56 to your computer and use it in GitHub Desktop.
ODG - Kotlin: Avoiding ConcurrentModificationException
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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