![]() |
VOOZH | about |
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.
If we know the exact position (index) of an element in a list, we can directly retrieve it.
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:
Output:
GeeksforGeeksIf the index might be invalid (e.g., larger than list size), Kotlin provides safe methods to avoid exceptions.
Example:
Output:
Element index not found
null
We can also retrieve first and last element from the list below two methods -
Example:
Output:
GeeksforGeeks
Portal
Using first() and last() method, we can retrieve the elements matching a given predicate.
Example:
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.
Output:
null
null
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:
Output:
Computer We can also check if an element exists in the collection.
Example:
Output:
false
true
true
false
true