jasitaly.blogg.se

Kotlin loop range
Kotlin loop range




kotlin loop range

10.In this article, you will learn about kotlin control flow statements like if, if-else, when and looping statements like for, while, do-while loops. We can use sortWith() and sortedWith() for sorting of lists using a Comparator object as an argument.įor a more in-depth look into sort operations while working with lists in Kotlin, refer to our Guide to Sorting in Kotlin article. If we want to return a list after sorting, we can use the sortedBy() and sortedByDescending() methods. The collection must be a mutable list since methods will use the natural order of the elements and will sort in-place. We can use sortBy() and sortByDescending() methods to sort lists based on specific properties of a given object. Val sortedCountriesDescending = countries.sortedDescending() If we want to return a list after sorting, we can use sorted() and sortedDescending() methods: val sortedCountriesAscending = countries.sorted()

kotlin loop range

So, the collection must be a mutable list. These methods will use the natural order of the elements and will sort in-place. Val sortCitiesDescending = cities.sortDescending() We can use sort() and sortDescending() methods to sort lists in Kotlin in ascending and descending order, respectively: val sortCitiesAscending = cities.sort() Let’s take a look at how the slice() method works: val sliceListUsingIndices = countries.slice(1.4)ĪssertEquals(4, sliceListUsingIndices.size) val sliceListUsingCollection = countries.slice(listOf(1, 4))ĪssertEquals(2, sliceListUsingCollection.size) 7. Unlike subList(), this method will create a new list with the subset of elements. We can use the slice() method to retrieve part of the list based on indices. Moreover, the Collection interface provides another method to retrieve parts of the list. Let’s have a look at an example to create a sublist: val subList = countries.subList(1, 4) So, any structural changes in the original list make the behavior of the view undefined. The subList() method returns a view of the original list and will change with it. The parameters for the method are used to define a specified range of the list between the fromIndex (inclusive) and toIndex (exclusive).

kotlin loop range

We can use the subList() method to retrieve a part of the list.






Kotlin loop range