Retrieve Single Elements In Kotlin
Last Updated :
21 Oct, 2021
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" )
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" )
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" )
println(list.first())
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" )
println(numbers.first { it.length > 5 })
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" )
println(numbers.firstOrNull { it.length > 9 })
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" )
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" )
println(list.contains( "For" ))
println(list.containsAll(listOf( "A" , "Computer" )))
println(list.isEmpty())
println(list.isNotEmpty())
}
|
Output:
false
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
Kotlin Collections Ordering
There are certain collections where the order of the elements is important. If you take lists, two lists are never equal if they are ordered differently inspite of having same elements.In Kotlin, there are different ways of ordering the elements. Most built-in types are comparable: -Numeric types fo
4 min read
Triple in Kotlin
In programming, we call functions to perform a particular task. The best thing about function is that we can call it any number of times and it returns some value after computation i.e. if we are having add() function then it always returns the sum of both the numbers entered. But, functions have so
4 min read
Implement Lazy List in Kotlin
If the value of an element or expression is not evaluated when it's defined, but rather when it is first accessed, it is said to be lazily evaluated. There are many situations where it comes in handy. For example, you might have a list A and you want to create a filtered list from it, let's call it
3 min read
Overriding Rules in Kotlin
In any object-oriented programming language, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. You decided your new class has to redefine one of the methods inherited
3 min read
Implement Universal Image Loader Library in Android using Kotlin
Universal Image Loader library is also referred to as (UIL). It is similar to Picasso and Glide which is used to load the images from the URL within our image view inside our android application. This image loading library has been created to provide a powerful, flexible, and customizable solution t
4 min read
TextView in Kotlin
Android TextView is simply a view that are used to display the text to the user and optionally allow us to modify or edit it. First of all, open Kotlin project in Android Studio. Following steps are used to create Steps to Implement TextViewSteps by Step implementation for creating an application wh
3 min read
Dynamic TextView in Kotlin
Android TextView is an user interface that is used to display some text to the user. In this article we will be discussing how to programmatically create a TextView in Kotlin . Step by Step ImplementationStep 1: Create a new projectLetâs start by first creating a project in Android Studio. To do so,
2 min read
Implement Interface in Kotlin
Interfaces in Kotlin can contain declarations of abstract methods, as well as method implementations. What makes them different from abstract classes is that interfaces cannot store a state. They can have properties, but these need to be abstract or provide accessor implementations. Basic Interface
3 min read