Open In App

Retrieve Single Elements In Kotlin

Improve
Improve
Like Article
Like
Save
Share
Report

Kotlin Collections allows to retrieve single elements with respect to different conditions. It totally depends on what kind of Collection is used to store the data. The elements of a collection can be retrieved by position, condition, randomization and with respect to the existence of that element in the list. 
 

Retrieving by Position –

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.
Kotlin program of using elementAt() method – 
 

Java




fun main(args: Array<String>) {
    val list=listOf("GeeksforGeeks","A","Computer","Science","Portal")
    // we know the place of GeeksforGeeks thus we use
    //elementAt() method
    println(list.elementAt(0))
}


Output: 
 

GeeksforGeeks

 
There are number of method used to retrieve an element from the list but to avoid exception when retrieving non-existing elements we should use safe methods. Two of the methods are:
elementAtOrElse(index){lambda expression}: – It is an addition over elementAt() and executes lambda expression when the index is not found. 
elementAtOrNull(index): – It is an addition over elementAt() and returns null when the index is not found.
Kotlin program of retrieving element using safe cast – 
 

Java




fun main(args: Array<String>) {
    val list=listOf("GeeksforGeeks","A","Computer","Science","Portal")
    // we are trying to access the elements out of bounds
    //one will give out null output and other will execute
    //print statement
    println(list.elementAtOrNull(5))
    println(list.elementAtOrElse(5){"Element index not found"})
}


Output: 
 

null
Element index not found

  
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.
Kotlin program of using first() and last() methods – 
 

Java




fun main(args: Array<String>) {
    val list=listOf("GeeksforGeeks","A","Computer","Science","Portal")
    // accessing the first element
    println(list.first())
    // accessing the last element
    println(list.last())
}


Output: 
 

GeeksforGeeks
Portal

 

Retrieving by condition –

Using first() and last() method, we can retrieve the elements matching a given predicate. 
 

Java




fun main(args: Array<String>) {
    val numbers = listOf("Geeks","for","Geek","A","Computer","Science","Portal")
    // retrieve the first element having string length > 5
    println(numbers.first { it.length > 5 })
    // retrieve the last element start with "G"
    println(numbers.last { it.startsWith("G") })
}


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. 
 

Java




fun main(args: Array<String>) {
    val numbers = listOf("Geeks","for","Geek","A","Computer","Science","Portal")
    // retrieve the first element having string length > 5
    println(numbers.firstOrNull { it.length > 9 })
    // retrieve the last element start with "G"
    println(numbers.lastOrNull { it.startsWith("B") })
}


Output: 
 

null
null

 

Random Retrieving –

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: – 
 

Java




fun main(args: Array<String>) {
    val strings = listOf("Geeks","for","Geek","A","Computer","Science","Portal")
    //Example of random outputs of letters in list new each time
    println(strings.random())
}


Output: 
 

Computer (output can be same or different)

 

Checking existence –

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.
Kotlin program of checking existence of string in a list – 
 

Java




fun main(args: Array<String>) {
    val list=listOf("Geeks","for","Geek","A","Computer","Science","Portal")
    //checking the string is in list or not
    println(list.contains("For"))
    println(list.containsAll(listOf("A", "Computer")))
    println(list.isEmpty())
    println(list.isNotEmpty())
}


Output: 
 

false
true
false
true

 



Last Updated : 21 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads