1. Why removing during iteration often breaks the program
Imagine you’re walking down a long corridor counting doors. If someone, while you’re counting, suddenly shifts the walls, removes doors, and swaps them around, you’ll either lose track, start skipping doors, or smack your forehead (with an exception playing the role of the forehead). Collections work the same way: iteration is a process that assumes the data structure is not being “rebuilt” under your feet.
The main reason removing during iteration is dangerous is that the for mechanism (via an iterator) expects the collection not to change “outside the rules”. Kotlin/JVM collections can often detect this kind of interference and respond with a ConcurrentModificationException. Sometimes there is no exception, but a logic error appears: you remove an element, indices shift, and the next element “slips past the check”.
In this lecture, it’s important to remember a practical formula: iteration and modification of a collection must be coordinated by the same mechanism. If you iterate with an iterator, the iterator should remove. If you iterate by indices, you must remove in a way that doesn’t “shift” the indices of elements you haven’t visited yet.
Forbidden pattern: remove(...) inside for (x in list)
Let’s start with the most popular “sin”, which looks logical, readable, and… sometimes works right up until the first real scenario. The logic seems ironclad: “I iterate elements; if an element is bad, I remove it.” But “iterate” and “remove” at that moment use different internal mechanisms, and they never agreed on anything.
fun main() {
val items = mutableListOf("keep", "remove", "keep")
for (x in items) {
if (x == "remove") {
items.remove(x) // dangerous
}
}
println(items)
}
On the JVM, this code often ends with a ConcurrentModificationException: the iterator notices the collection was modified “behind its back” and stops in the most honest way—by crashing. Even if you get lucky and no exception happens, you must not rely on that: the behavior depends on the collection implementation and the specific situation.
It’s important to catch the idea: for (x in items) uses an iterator under the hood, while items.remove(x) modifies the collection directly. It’s like driving by navigation while someone rearranges the roads in real time.
Forbidden pattern: removing by indices from left to right
The second trap is more common among people who already realized that “you can’t remove inside for (x in list)”, and decided: “Fine, I’ll iterate by indices—I control everything!” You do gain control, but along with it comes a new problem: removal shifts elements to the left, while your index keeps growing to the right.
Let’s look at an example where we need to remove all "remove":
fun main() {
val items = mutableListOf("keep", "remove", "remove", "keep")
for (i in 0..items.lastIndex) {
if (items[i] == "remove") {
items.removeAt(i) // dangerous when moving left to right
}
}
println(items)
}
Even if this code doesn’t crash due to lastIndex changing (and it easily can crash with an out-of-bounds at the end), there’s a subtler effect: when you remove items[1], the former items[2] moves into position 1. But the loop is already preparing to move to i = 2, and you simply won’t check that “moved” element. The result: some elements won’t be removed, and you get a bug with no exception. The favorite kind of bugs: “the program doesn’t crash, but it lies”.
To stop suffering like this, remember: if you remove by indices, you must iterate from the end to the beginning.
2. Strategy: removal via MutableIterator.remove()
Now comes the moment when collections suddenly become nice. Kotlin has a special iterator type for mutable collections—MutableIterator. It extends the regular Iterator and adds the remove() method, which removes the “current” element correctly, i.e., in coordination with the iteration process.
The key idea: if iteration is controlled by an iterator, then the iterator should do the removing.
Here’s a safe way to remove while iterating a list:
fun main() {
val items = mutableListOf("a", "remove", "b")
val it = items.iterator()
while (it.hasNext()) {
val x = it.next()
if (x == "remove") {
it.remove()
}
}
println(items) // [a, b]
}
Notice the “ritual”: first we call next(), so the iterator “points a finger” at the current element, and only after that can we call remove(). That’s why people often say remove() removes the last element that was returned by next().
The iterator is one-time use
After you reach the end, that iterator is “exhausted”. If you need to iterate the collection again, create a new iterator via items.iterator(). This is not an error and not “wasteful”—it’s the normal iteration model.
Example from a mini app: cleaning up blank strings
Let’s continue in a practical style: imagine in a project we have a shopping list, and the user sometimes adds junk (empty strings, whitespace). We want a cleanup command that removes blank entries.
fun cleanupBlankItems(items: MutableList<String>) {
val it = items.iterator()
while (it.hasNext()) {
val name = it.next()
if (name.isBlank()) {
it.remove()
}
}
}
This function is small but useful: it demonstrates exactly the case where removal happens “by condition” during iteration, and here the iterator is the most reliable tool.
Contract of MutableIterator.remove(): how not to break the rules
The very idea of “remove via the iterator” sounds like salvation, but it comes with rules. And these rules aren’t of the “preferably” kind—they’re of the “otherwise there will be an exception” kind. If you violate the contract, collections become angry again, only this time for a reason.
The most common problem is calling remove() twice in a row without a new next(). Let’s show how you shouldn’t do it:
fun main() {
val items = mutableListOf("remove", "x")
val it = items.iterator()
it.next()
it.remove()
// it.remove() // not allowed: there was no second next()
println(items) // [x]
}
The logic is simple: after remove() the iterator has already removed the “last yielded element”. To remove something again, the iterator must yield another element via next(). If you try to remove again, the iterator doesn’t understand “what exactly you want to remove” and rightfully complains.
In a real project, this usually surfaces not as explicitly as above, but when complex branching logic appears inside the loop. So a useful habit is to keep the loop body simple: “get element → check condition → remove if needed”.
3. Strategy: removal by indices from right to left
Sometimes an iterator is not the most convenient option. For example, your logic depends on the index: you remove “every third element”, remove a range, or you need to print the element number to the user. In such cases it’s easier to think in indices. But then you must remove in a way that removal does not affect the elements you haven’t checked yet.
The trick here is that list indices go from 0 to lastIndex, where lastIndex == size - 1. If you iterate from the end to the beginning, removing an element does not shift the elements to its left. That means the indices of your “not yet checked” elements do not change.
Here’s a safe example:
fun main() {
val items = mutableListOf("keep", "remove", "remove", "keep")
for (i in items.lastIndex downTo 0) {
if (items[i] == "remove") {
items.removeAt(i)
}
}
println(items) // [keep, keep]
}
Mini diagram: why right-to-left works
flowchart TD
A[Idem i sleva napravo] --> B["Udalyayem items[i]"]
B --> C[Elementy sprava sdvigayutsya vlevo]
C --> D[Sleduyushchiy i propuskayet odin element]
D --> E[Logicheskaya oshibka]
A2[Idem i sprava nalevo] --> B2["Udalyayem items[i]"]
B2 --> C2[Sdvigayutsya tol'ko elementy sprava, no sprava uzhe vsyo provereno]
C2 --> D2[Neproverennye elementy sleva ne menyayut indeks]
D2 --> E2[Logika korrektna]
4. How to choose a strategy in real code
In practice, you’ll choose a strategy not by beauty, but by what you need in a specific operation. To avoid keeping all this in your head as a “gut feeling”, it’s handy to have a small reminder table.
| Situation | Best fit | Why |
|---|---|---|
| Remove elements by condition; index doesn’t matter | |
Iteration and removal are done by the same “device”, fewer chances to make a mistake |
| Remove from MutableList, but the logic depends on the index | Loop for (i in lastIndex downTo 0) + removeAt(i) | Indices of unchecked elements don’t shift |
| Remove from a MutableMap while iterating | Iterator over entries + remove() | Removal of the “current entry” is coordinated with iteration |
| Remove a single element “by value” without iterating | |
No iteration is needed, so there are no conflicts |
Note: the table doesn’t say “always do it this way”. It says: “if you’re already in situation X, here is the most predictable path”.
5. Safe removal from a MutableMap while iterating
A Map is not a list—you can’t iterate it by indices. But sometimes you really want to remove from a MutableMap while iterating. For example, in our app we might have a MutableMap<String, Int> as a “warehouse”: product → quantity. And we want to clean out products whose quantity became 0.
If you try to do stock.remove(key) inside for ((k, v) in stock), you get the same conflict: “iteration via iterator, removal directly”. The correct option is an iterator over entries:
fun removeZeroStock(stock: MutableMap<String, Int>) {
val it = stock.entries.iterator()
while (it.hasNext()) {
val entry = it.next()
if (entry.value == 0) {
it.remove()
}
}
}
Why entries specifically? Because Map.Entry gives you both the key and the value at once, without a second lookup. And an iterator over entries can correctly remove the current pair. Conceptually, it’s the same principle as with a list: the one who iterates should remove.
6. Integrating into an app: data cleanup operations
In real programs, removal during iteration rarely exists by itself. Usually it lives inside a “maintenance operation”: delete invalid records, remove empty elements, delete completed tasks, clean out zero stock. That’s why it’s useful to wrap such chunks as separate functions—small and testable.
Suppose, in our console app, the shopping state is stored like this: each purchase is a Pair<String, Int>, where first is the product name and second is the quantity. (We haven’t covered classes yet, so we do it without a data class.)
Let’s make a function that removes purchases with quantity <= 0. This is a classic case of “remove many elements by condition”, so an iterator fits perfectly:
fun removeNonPositive(items: MutableList<Pair<String, Int>>) {
val it = items.iterator()
while (it.hasNext()) {
val item = it.next()
if (item.second <= 0) {
it.remove()
}
}
}
And now a situation where indices are more convenient: suppose we want to remove all elements with the name "tmp" (the user added temporary entries), but we also want to print which exact lines we removed, with their “number in the list at the moment of removal”. Then we can go right to left, and the numbers “to the right” of us no longer matter:
fun removeAllTmp(items: MutableList<String>) {
for (i in items.lastIndex downTo 0) {
if (items[i] == "tmp") {
items.removeAt(i)
}
}
}
Here it’s important not to try to make it “prettier” and replace it with left-to-right iteration: right-to-left is not a whim, it’s a correctness guarantee.
remove(value) and removeAt(index): don’t mix up the meaning
When you write code that “removes”, it’s easy to start confusing: are you removing by value or by position? This is especially noticeable in command-line apps, where the user enters remove 3 and expects “remove the third element”, but you accidentally do “remove the element with the value "3"”.
A MutableList usually has two different operations: removal by value and removal by index. In Kotlin this is reflected directly in the names: removeAt(i) removes by position, while remove(x) removes by value. When you design commands, decide the semantics in advance: either the remove command deletes by number (then you need removeAt and a check that i in indices), or by value (then remove(value)), or you have two different commands.
This matters specifically in today’s context: if you remove “many elements” by condition, almost always you will either call removeAt many times or use an iterator. And if you remove exactly one element by value, you don’t need iteration at all.
7. Common mistakes in safe removals
Mistake #1: removing via the collection inside for (x in collection).
It looks natural, but it conflicts with how for works: under the hood it uses an iterator, while you change the collection structure directly. A common outcome is ConcurrentModificationException, and sometimes even worse: “just weird behavior”. The reliable solution is to remove either via MutableIterator.remove(), or not remove during iteration at all.
Mistake #2: iterating by indices left to right and doing removeAt(i) inside the loop.
Technically you “control everything”, but removal shifts elements and you easily skip part of the collection or go out of bounds. If you choose the index style, there is one safe rule: remove right-to-left via for (i in lastIndex downTo 0).
Mistake #3: calling it.remove() outside the contract, e.g. twice in a row.
MutableIterator.remove() removes the element that was last returned by next(). If you call remove() before next() or repeat remove() without a new next(), the iterator can’t correctly determine the removal target and will throw an exception. The discipline is simple: “next() → check → maybe remove()”.
Mistake #4: trying to remove from a Map while iterating keys, and in parallel doing map.remove(key).
Even if it seems like “I remove by key, that’s logical”, the problem is the same: iteration and removal use different mechanisms. The reliable path: val it = map.entries.iterator() and removal via it.remove().
Mistake #5: confusing “index” and “user-facing number”.
The user thinks “first element” and means 1, while the list thinks “first element” and means index 0. If you accept a delete command by number, always do index = number - 1 and check index in items.indices, otherwise you’ll either delete the wrong element or crash.
GO TO FULL VERSION