Retrieve Single Elements In Kotlin
Last Updated :
15 Jun, 2025
In Kotlin, we can easily retrieve single elements from a collection in many ways depending on our need—by position, by condition, randomly, or by checking if the element exists. The method we choose depends on the type of collection (like List, Set, etc.) and the situation.
1. Retrieving by Position
If we know the exact position (index) of an element in a list, we can directly retrieve it.
a). elementAt(index)
elementAt() takes index of the element and retrieve it from the list. The index of the list starts from 0 and goes till n-1 where n is no of elements within the list. It is the most simple and easiest way to retrieve the element and is only preferred when the position of the needed element is known in advance.
Example:
Kotlin
fun main() {
val list = listOf("GeeksforGeeks", "Kotlin", "Portal")
println(list.elementAt(0)) // prints the first element
}
Output:
GeeksforGeeks
b). Safe ways to retrieve by index
If the index might be invalid (e.g., larger than list size), Kotlin provides safe methods to avoid exceptions.
- elementAtOrElse(index) { lambda } - If index is invalid, lambda block is executed.
- elementAtOrNull(index) - Returns null if index is out of bounds.
Example:
Kotlin
fun main() {
val list = listOf("GeeksforGeeks", "Kotlin", "Portal")
println(list.elementAtOrElse(5) { "Element index not found" })
println(list.elementAtOrNull(5)) // returns null
}
Output:
Element index not found
null
2. Retrieving First and Last Elements
We can also retrieve first and last element from the list below two methods -
- first(): - It is used to retrieve the first element from the list i.e having the index 0.
- last(): - It is used to retrieve the last element of the list i.e having the index n-1 where n is the size of the list.
Example:
Kotlin
fun main() {
val list = listOf("GeeksforGeeks", "Kotlin", "Portal")
println(list.first()) // First element
println(list.last()) // Last element
}
Output:
GeeksforGeeks
Portal
3. Retrieving by Condition (Predicate) -
Using first() and last() method, we can retrieve the elements matching a given predicate.
Example:
Kotlin
fun main() {
val list = listOf("Computer", "Kotlin", "Geek")
println(list.first { it.startsWith("C") }) // First word starting with 'C'
println(list.last { it.endsWith("k") }) // Last word ending with 'k'
}
Output:
Computer
Geek
Both functions throw exceptions, if no elements found matching the predicate. To avoid exception, we use firstOrNull() and lastOrNull() and they will return null if no matching elements are found.
Kotlin
fun main() {
val list = listOf("Computer", "Kotlin", "Geek")
println(list.firstOrNull { it.startsWith("Z") }) // no such element
println(list.lastOrNull { it.endsWith("z") }) // no such element
}
Output:
null
null
4. Random Element Retrieval
If we want to retrieve an arbitrary element from the list we can use random() function.
random() :- It returns a random element from the collection.
Example:
Kotlin
fun main() {
val list = listOf("Computer", "Kotlin", "Geek")
println(list.random()) // Output can vary each time
}
Output:
Computer
5. Checking Existence of Elements
We can also check if an element exists in the collection.
- contains(element): -It is used to check if an element is in the list or not. It returns true if element is there else it returns false.
- containsAll(elements[]): - It is used to check if all the elements are in the list or not. It returns true if all the elements are there else it returns false.
- in keyword: - It is used to check if all the elements are in the list or not. It returns true if the element are there else it returns false.
- isEmpty(): - It is used to check if the list is empty or not. It returns true if the elements are not in list else it returns false.
- isNotEmpty(): - It is used to check if the list is empty or not. It returns true if the elements are in list else it returns false.
Example:
Kotlin
fun main() {
val list = listOf("Geeks", "Kotlin", "Portal")
println("Java" in list)
println("Kotlin" in list)
println(list.containsAll(listOf("Kotlin", "Portal")))
println(list.isEmpty())
println(list.isNotEmpty())
}
Output:
false
true
true
false
true
Similar Reads
Kotlin | Retrieve Collection Parts The slice function allows you to extract a list of elements from a collection by specifying the indices of the elements you want to retrieve. The resulting list contains only the elements at the specified indices. The subList function allows you to retrieve a sublist of a collection by specifying th
5 min read
Singleton Class in Kotlin Singleton Class in Kotlin is also called as the Singleton Object in Kotlin. Singleton class is a class that is defined in such a way that only one instance of the class can be created and used everywhere. Many times we create the two different objects of the same class, but we have to remember that
4 min read
Restricting Class Hierarchies in Kotlin Kotlin is a statically typed, general-purpose programming language developed by JetBrains, that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011 and is a new language for the JVM. Kotlin is an object-oriented language, and a âbetter
3 min read
Triple in Kotlin In programming, we often use functions to perform specific tasks. One of the main benefits of functions is that we can call them as many times as we need, and they return a result after performing some computation. For example, an add() function will always return the sum of two numbers we pass to i
3 min read
Implement Instant Search Using Kotlin Flow Operators A flow is a type in coroutines that can emit multiple values sequentially, as opposed to suspend functions, which only return a single value. A flow, for example, can be used to receive real-time updates from a database. Flows are constructed on top of coroutines and can return multiple values. A fl
4 min read
Code Formatting in Kotlin using ktlint As we all know about the kotlin language which is recommended by google particularly for android app development, and of course, it made the life of android app developers easier. But if you are a beginner in this field then you may not know that you need to write the codes in the desired format. an
4 min read