Kotlin - Sorting Arrays Example

This example shows how to sort Kotlin Arrays.

Kotlin - Sorting Arrays Example

The below example sorts an array in ascending order with sortedArray() method and descending order with sortedArrayDescending() method. The methods create new sorted arrays.
package net.javaguides.kotlin.examples

import java.util.Arrays

fun main(args: Array < String > ) {
    val nums = arrayOf(7, 3, 3, 4, 5, 9, 1, 8, 7)

    // Sort and return a new array 
    val sortedNums = nums.sortedArray()
    println(Arrays.toString(sortedNums))

    // Sort an array in descending order
    val sortedNumsDesc = nums.sortedArrayDescending()
    println(Arrays.toString(sortedNumsDesc))

    // Sort an array in ascending order in a range
    nums.sort(0, 5)
    println("Sorted array from index 0 to 5 : " + Arrays.toString(nums))
}

Sort an array of custom objects using a comparator

Use sortWith function, that takes one comparator as a parameter to sort an array of custom objects.
package net.javaguides.kotlin.examples

import java.util.Arrays

fun main(args: Array < String > ) {
    val students = arrayOf(Student("Ramesh", 5), Student("John", 2), Student("Tony", 1))
    println("Original array : ")
    students.forEach {
        println(it)
    }
    students.sortWith(Comparator {
        s1: Student,
        s2: Student - > s1.rank - s2.rank
    })
    println("Final array : ")
    students.forEach {
        println(it)
    }
}

data class Student(val name: String, val rank: Int)
Output:
Original array : 
Student(name=Ramesh, rank=5)
Student(name=John, rank=2)
Student(name=Tony, rank=1)
Final array : 
Student(name=Tony, rank=1)
Student(name=John, rank=2)
Student(name=Ramesh, rank=5)

Comments