Retrieve Single Elements In Kotlin

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 –



filter_none

edit
close

play_arrow

link
brightness_4
code

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))
}

chevron_right


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 –

filter_none

edit
close

play_arrow

link
brightness_4
code

fun main(args: Array<String>) {
    val list=listOf("GeeksforGeeks","A","Computer","Science","Portal")
    // we are trying to access the elemtents 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"})
}

chevron_right


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 –

filter_none

edit
close

play_arrow

link
brightness_4
code

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())
}

chevron_right


Output:

GeeksforGeeks
Portal

Retrieving by condition –

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


filter_none

edit
close

play_arrow

link
brightness_4
code

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") })
}

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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") })
}

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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())
}

chevron_right


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 –

filter_none

edit
close

play_arrow

link
brightness_4
code

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())
}

chevron_right


Output:

false
true
false
true


My Personal Notes arrow_drop_up

Im a final year MCA student at Panjab University, Chandigarh, one of the most prestigious university of India I am skilled in various aspects related to Web Development and AI I have worked as a freelancer at upwork and thus have knowledge on various aspects related to NLP, image processing and web

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.