![]() ![]() 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). In this Kotlin Tutorial – Kotlin list forEach, we have learnt how to perform a block of statement for each element of the list, with examples.We can use the subList() method to retrieve a part of the list. Price of book, Kotlin Android Tutorial is 2 Println("Price of book, $")ĭata class Book(val name: String = "", val price: Int = 0) Val book2 = Book("Kotlin Android Tutorial", 2) In the following example, we shall consider list of Data Class objects and print a message for each item of the List using forEach. In the following example, we shall print each item of an Integer List using forEach.Įxample 3 – Kotlin List forEach – Custom Object Var listB = listOf("Example", "Program", "Tutorial")Įxample 2 – Kotlin List forEach – Integer In the following example, we shall print each item of String List using forEach. Inside the code block of forEach, the item could be referenced as it. Kotlin List foreach is used perform the given action on each item of the list. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |