Kotlin List sortedWith()
Syntax & Examples
Syntax of List.sortedWith()
The syntax of List.sortedWith() extension function is:
fun <T> Iterable<T>.sortedWith( comparator: Comparator<in T> ): List<T>This sortedWith() extension function of List returns a list of all elements sorted according to the specified comparator.
✐ Examples
1 Example
In this example,
- We create a list named
listcontaining the strings['banana', 'apple', 'cherry']. - We call the
sortedWithfunction onlist, sorting the elements according to the length of each string. - The result, which is the sorted list
['apple', 'banana', 'cherry'], is stored insortedList. - Finally, we print the
sortedListto standard output using theprintlnfunction.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("banana", "apple", "cherry");
val sortedList = list.sortedWith(compareBy { it.length });
println(sortedList);
}Output
[apple, banana, cherry]
2 Example
In this example,
- We define a data class
Personwithnameandageproperties. - We create a list named
peoplecontaining instances ofPerson. - We call the
sortedWithfunction onpeople, sorting the elements according to theageproperty of eachPersonobject. - The result, which is the sorted list of
Personobjects by age, is stored insortedPeople. - Finally, we print the
sortedPeopleto standard output using theprintlnfunction.
Kotlin Program
fun main(args: Array<String>) {
data class Person(val name: String, val age: Int)
val people = listOf(Person("Alice", 29), Person("Bob", 35), Person("Charlie", 25));
val sortedPeople = people.sortedWith(compareBy { it.age });
println(sortedPeople);
}Output
[Person(name=Charlie, age=25), Person(name=Alice, age=29), Person(name=Bob, age=35)]
3 Example
In this example,
- We create a list named
listcontaining the integers[3, 1, 4, 1, 5, 9, 2, 6]. - We call the
sortedWithfunction onlist, sorting the elements in ascending order. - The result, which is the sorted list
[1, 1, 2, 3, 4, 5, 6, 9], is stored insortedList. - Finally, we print the
sortedListto standard output using theprintlnfunction.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(3, 1, 4, 1, 5, 9, 2, 6);
val sortedList = list.sortedWith(compareBy { it });
println(sortedList);
}Output
[1, 1, 2, 3, 4, 5, 6, 9]
Summary
In this Kotlin tutorial, we learned about sortedWith() extension function of List: the syntax and few working examples with output and detailed explanation for each example.