To sort a list in a custom order in Kotlin, you can create a custom Comparator that defines the order in which elements should be sorted. You can then use the sortedWith() function on the list, passing in your custom Comparator to sort the list according to the custom order specified. This allows you to sort the list based on your own criteria rather than the default sorting order.
How to customize the order of sorting in Kotlin?
In Kotlin, you can customize the order of sorting by using a Comparator. Here's an example of how you can customize the sorting order of a list of objects based on a specific property:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
data class Person(val name: String, val age: Int) fun main() { val persons = listOf( Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35) ) val sortedPersons = persons.sortedWith(compareBy { it.age }) sortedPersons.forEach { println(it) } } |
In this example, we are sorting a list of Person objects based on their age property. The sortedWith(compareBy { it.age })
function call customizes the sorting order by comparing the age property of each Person object.
You can also customize the sorting order using multiple properties or custom logic inside the compareBy
block.
1
|
val sortedPersons = persons.sortedWith(compareBy({ it.age }, { it.name }))
|
This will first sort the list by age and then by name.
You can also write your custom Comparator by implementing the Comparator interface with a compare function.
1 2 3 4 5 6 7 8 9 |
val customComparator = Comparator { p1: Person, p2: Person -> when { p1.age > p2.age -> 1 p1.age < p2.age -> -1 else -> p1.name.compareTo(p2.name) } } val sortedPersons = persons.sortedWith(customComparator) |
In this example, we define a custom Comparator that first compares the age property of the Person objects and then compares the name property if the ages are equal.
These are some ways you can customize the order of sorting in Kotlin using comparators.
What is the difference between sort() and sorted() in Kotlin?
In Kotlin, sort() is a function that sorts a mutable collection in-place, meaning it modifies the original collection. It does not return a new sorted collection, but instead sorts the elements within the existing collection.
On the other hand, sorted() is a function that creates a new sorted collection from an existing collection. It does not modify the original collection, but rather returns a new collection with the elements sorted according to the provided comparator.
In summary, sort() sorts the elements in-place, while sorted() creates a new sorted collection.
What is the default sorting order in Kotlin?
In Kotlin, when sorting elements using the sorted
function or sortBy
function, the default sorting order is ascending order. This means that elements will be sorted from smallest to largest based on their natural ordering or custom comparator provided.