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() 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). We can use the subList() method to retrieve a part of the list.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |