How to remove item from ArrayList in Kotlin

removeAt(0) removes the first element from the first list and returns it. arrayListOf then uses that removed item to create a new (the second) list.

arrayone then contains: b and c. arraytwo then contains a.

You may want to use drop instead, if you didn’t want to touch the first list and if you only wanted to add the remaining items to the new list, e.g.:

var arrayone: ArrayList<String> = arrayListOf("a","b","c")

val arraytwo = arrayone.drop(1)

for (item in arraytwo) {
  println(item) // now prints all except the first one...
}
// arrayone contains: a, b, c
// arraytwo contains: b, c

Or use dropLast(1) if you want to drop only the last item. Or use dropWhile/dropLastWhile if you have a condition to apply and drop all until/upto that condition…

If you really want to remove items from the first and add only the removed ones to the second list, then your current approach is ok. If you however wanted to remove items at specific index and have a new list instead just containing the not-removed ones, you need to construct a copy of the first list first and then apply your removeAt on that list, e.g.:

val arraytwo = arrayone.toMutableList().apply { 
  removeAt(0)
}
// or without the apply:
arraytwo.removeAt(0)

Or you may use filterIndexed to solve that:

val arraytwo = arrayone.filterIndexed { index, _ ->
  index != 1 // you can also specify more interesting filters here...
} // filter, map, etc. all return you a new list. If that list must be mutable again, just add a .toMutableList() at the end

By using filterIndexed, filter, drop, etc. you ensure that the first list is kept untouched. If you didn’t want to touch the first list in the first place, you may rather want to use listOf or toList, i.e. just a List as type instead, which does not expose mutable functions (check also Kotlin reference regarding Collections: List, Set, Map).

Maybe you are also interested in filter/filterNot and then soon in minus or similar functions to remove unwanted items without index.

Leave a Comment

tech