
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove Item from ArrayList in Kotlin
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:
" + arrayone) println("
=====================
") // drop the first element val arraytwo = arrayone.drop(1) println("After dropping the first element:
" + 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]
Advertisements