How to remove an item from an ArrayList in Kotlin?

Kotlin Mobile DevelopmentApps/Applications

In this article we will see how we can remove an item from an ArrayList using Kotlin library function. In order to do that, we will take the help of a library function called drop(). The function definition looks as follows −

fun <T> Array<out T>.drop(n: Int): List<T>
(source)

It takes array and a position as an input and it returns a list containing all the elements except the first n elements.

Example – drop() in Kotlin

In this example, we will remove the first element from a list using drop().

fun main(args: Array<String>) {
   var arrayone: ArrayList<String> = arrayListOf("mango","jam","apple","lemon","spice")
   println("The ArrayList is:\n" + arrayone)

   println("\n=====================\n")

   // drop the first element
   val arraytwo = arrayone.drop(1)
   println("After dropping the first element:\n" + arraytwo)
}

Output

On execution, it will produce the following output −

The ArrayList is:
[mango, jam, apple, lemon, spice]
=====================
After dropping the first element:
[jam, apple, lemon, spice]

Example – Remove specific element from a list using filterTo()

In this example, we will remove a specific item from a given list.

fun main() {
   var arr = arrayOf<String>("mango","jam","apple","lemon","spice")
   val arraytwo = arrayListOf<String>()

   // Remove "jam" from the list
   arr.filterTo(arraytwo, { it != "jam" })
   println(arraytwo)
}

Output

It will produce the following output −

[mango, apple, lemon, spice]
raja
Updated on 01-Mar-2022 11:13:33

Advertisements