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 list containing the strings ['banana', 'apple', 'cherry'].
  • We call the sortedWith function on list, sorting the elements according to the length of each string.
  • The result, which is the sorted list ['apple', 'banana', 'cherry'], is stored in sortedList.
  • Finally, we print the sortedList to standard output using the println function.

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 Person with name and age properties.
  • We create a list named people containing instances of Person.
  • We call the sortedWith function on people, sorting the elements according to the age property of each Person object.
  • The result, which is the sorted list of Person objects by age, is stored in sortedPeople.
  • Finally, we print the sortedPeople to standard output using the println function.

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 list containing the integers [3, 1, 4, 1, 5, 9, 2, 6].
  • We call the sortedWith function on list, sorting the elements in ascending order.
  • The result, which is the sorted list [1, 1, 2, 3, 4, 5, 6, 9], is stored in sortedList.
  • Finally, we print the sortedList to standard output using the println function.

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.