Hey Guys, I am looping and deleting the element fr...
# android
v
Hey Guys, I am looping and deleting the element from the same list in kotlin. So I am getting error so what is way of doing that.
Copy code
Exception in thread "main" java.util.ConcurrentModificationException
	at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1013)
	at java.base/java.util.ArrayList$Itr.next(ArrayList.java:967)
	at ChipDataKt.main(ChipData.kt:72)
	at ChipDataKt.main(ChipData.kt)
stackoverflow 2
Copy code
var categoryList: MutableList<Categories>? = null
fun main() {
    categoryList = categoriesList().toMutableList()
    categoryList?.add(0, Categories("0", "physical-ktm", listOf(SubTopic("1", "vivek"))))
    println("After Add")
    categoryList?.forEachIndexed { index, categories ->
        println("$index index -> $categories")
    }

    categoryList?.mapIndexed { index, categories ->
        if(categories.subTopic?.firstOrNull()?.title == "vivek"){
            categoryList?.removeAt(index)
        }
    }
    println("After operation")
    categoryList?.forEachIndexed { index, categories ->
        println("$index index -> $categories")
    }
}
Copy code
fun categoriesList() = listOf(
    Categories("21", "physical", listOf(SubTopic("1", "abc"), SubTopic("2", "bjhef"))),
    Categories("2211", "mind", listOf(SubTopic("1", "abc"), SubTopic("2", "bjhef"))),
    Categories("22131", "motorized", listOf(SubTopic("1", "abc"), SubTopic("2", "bjhef"))),
    Categories("2134124", "coordination", listOf(SubTopic("1", "abc"), SubTopic("2", "bjhef"))),
    Categories("211243", "animal-supported", listOf(SubTopic("1", "abc"), SubTopic("2", "bjhef"))),
)
Copy code
data class Categories(
    val id: String? = null, val title: String? = null, val subTopic: List<SubTopic>? = null
)

data class SubTopic(
    val id: String? = null, val title: String? = null, var priceId: String? = null
)
e
The error says it all. One of the fix is why not try using
filter
? E.g:
Copy code
val filteredCategoryList = categoryList?.filter { categories ->
    categories.subTopic?.firstOrNull()?.title != "vivek"
}
c
You cannot delete items while in a for loop. You need to use the `Iterator`‘s function https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
v
Thank you guys.