lmkawomen.blogg.se

Kotlin list find
Kotlin list find









For mutable lists, the standard library offers similar extension functions that perform the same ordering operations in place. In Collection Ordering, we describe operations that retrieve collection elements in specific orders. Val numbers = mutableListOf(1, 2, 3, 4, 3) You can also specify an index range to search in: in this case, the function searches only between two provided indices. If there is more than one element with the given value, the search can return any of their indices. If such an element exists, the function returns its index otherwise, it returns (-insertionPoint - 1) where insertionPoint is the index where this element should be inserted so that the list remains sorted. To search an element in a sorted list, call the binarySearch() function passing the value as an argument.

kotlin list find

It works significantly faster than other built-in search functions but requires the list to be sorted in ascending order according to a certain ordering: natural or another one provided in the function parameter. There is one more way to search elements in lists – binary search.

kotlin list find

index 0 is returned.Println(numbers.indexOfLast ) Note that we have two January objects available but the first object i.e. feb is not in the list, so it will return null and january is the first Month object with name January and days 31. We have only one April Month object in the list. Īpril is the Month object with name April and days 30.įinally, we are printing the objects that we got from find.

kotlin list find

Each find compares the name and days of the finding object in the predicate. We are finding three different months in this list. MonthList is a list of Month objects with five different objects. Month is a data class with three properties : String name, Integer days and Integer index. Data class Month ( val name : String, val days : Int, val index : Int ) fun main ( ) Explanation :











Kotlin list find