
One common way is to loop through the list and check if any user has age greater than 22 but why to write so much of code if kotlin has already done this for us. Find if any user has age greater than 22? All codes are tested on data class User(val name:String,val age:Int) val list = listOf( User("Yash",24), User("Dilpreet",22), User("himanshu",24), User("deepanshu",21), User("rohit",19), User("sonam",18) ) Q1. We will try to make it a question to answer discussion. Let’s define some basic data structure we will be using in this article. Let’s talk about some function that kotlin collection provides us.

In case of List, it's more idiomatic to use indexed access operator ( get() or ).One of the great feature kotlin provides us is passing a function as a parameter to other functions or storing function in a variable. The first element has the position 0, and the last one is (size - 1).ĮlementAt() is useful for collections that do not provide indexed access, or are not statically known to provide one.

Call it with the integer number as an argument, and you'll receive the collection element at the given position. Retrieve by positionįor retrieving an element at a specific position, there is the function elementAt(). However, such results are unpredictable to the caller unless they know the specific implementation of Set used. In such cases, the elements are still ordered somehow, so the functions that rely on the element positions still return their results. The order of a set of elements can also be unknown.

These can be the order of insertion (in LinkedHashSet), natural sorting order (in SortedSet), or another order. However, the Kotlin Set stores elements in certain orders. In turn, set is not an ordered collection by definition. For more details, see List-specific operations. In addition to functions described on this page, lists offer a wider set of ways to retrieve and search for elements by indices. Hence, every element of a list has its position that you can use for referring.

Functions described on this page apply to both lists and sets.Īs the definition of list says, a list is an ordered collection. Kotlin collections provide a set of functions for retrieving single elements from collections.
