Kotlin Array sorted Function

The sorted function in Kotlin is used to sort the elements of an array. This function is part of the Kotlin standard library and provides a straightforward way to order elements in an array either in ascending or descending order.

Table of Contents

  1. Introduction
  2. sorted Function Syntax
  3. Understanding sorted
  4. Examples
    • Basic Usage
    • Using sorted with Custom Types
    • Sorting in Descending Order
    • Using sortedBy and sortedWith
  5. Real-World Use Case
  6. Conclusion

Introduction

The sorted function returns a list containing all elements of the original array sorted in ascending order. It is a simple and effective way to sort arrays in Kotlin.

sorted Function Syntax

The syntax for the sorted function is as follows:

fun <T : Comparable<T>> Array<out T>.sorted(): List<T>

Parameters:

  • This function does not take any parameters.

Returns:

  • A list containing the sorted elements of the original array.

Understanding sorted

The sorted function sorts the elements of an array in natural order (ascending). If the array elements implement the Comparable interface, they can be sorted using this function. For custom sorting, Kotlin provides additional functions like sortedBy and sortedWith.

Examples

Basic Usage

To demonstrate the basic usage of sorted, we will create an array of integers and sort its elements in ascending order.

Example

fun main() {
    val numbers = arrayOf(5, 2, 9, 1, 5, 6)
    val sortedNumbers = numbers.sorted()
    println("Sorted numbers: $sortedNumbers")
}

Output:

Sorted numbers: [1, 2, 5, 5, 6, 9]

Using sorted with Custom Types

This example shows how to use sorted to sort an array of custom objects. The custom objects must implement the Comparable interface.

Example

class Person(val name: String, val age: Int) : Comparable<Person> {
    override fun compareTo(other: Person): Int {
        return this.age - other.age
    }

    override fun toString(): String {
        return "Person(name='$name', age=$age)"
    }
}

fun main() {
    val people = arrayOf(
        Person("Ravi", 25),
        Person("Anjali", 30),
        Person("Priya", 22)
    )

    val sortedPeople = people.sorted()
    println("Sorted people by age: $sortedPeople")
}

Output:

Sorted people by age: [Person(name='Priya', age=22), Person(name='Ravi', age=25), Person(name='Anjali', age=30)]

Sorting in Descending Order

This example demonstrates how to sort an array in descending order using the sortedDescending function.

Example

fun main() {
    val numbers = arrayOf(5, 2, 9, 1, 5, 6)
    val sortedNumbersDescending = numbers.sortedDescending()
    println("Sorted numbers in descending order: $sortedNumbersDescending")
}

Output:

Sorted numbers in descending order: [9, 6, 5, 5, 2, 1]

Using sortedBy and sortedWith

This example shows how to use sortedBy to sort an array based on a specific property and sortedWith to use a custom comparator.

Example

data class Person(val name: String, val age: Int)

fun main() {
    val people = arrayOf(
        Person("Ravi", 25),
        Person("Anjali", 30),
        Person("Priya", 22)
    )

    val sortedByName = people.sortedBy { it.name }
    println("Sorted people by name: $sortedByName")

    val sortedWithCustomComparator = people.sortedWith(compareBy { it.age })
    println("Sorted people by age with custom comparator: $sortedWithCustomComparator")
}

Output:

Sorted people by name: [Person(name='Anjali', age=30), Person(name='Priya', age=22), Person(name='Ravi', age=25)]
Sorted people by age with custom comparator: [Person(name='Priya', age=22), Person(name='Ravi', age=25), Person(name='Anjali', age=30)]

Real-World Use Case

Sorting Data for Display

In real-world applications, the sorted function can be used to sort data before displaying it to users, such as sorting a list of products by price or name.

Example

data class Product(val name: String, val price: Double)

fun main() {
    val products = arrayOf(
        Product("Laptop", 999.99),
        Product("Smartphone", 699.99),
        Product("Tablet", 299.99)
    )

    val sortedProducts = products.sortedBy { it.price }
    println("Products sorted by price: $sortedProducts")
}

Output:

Products sorted by price: [Product(name='Tablet', price=299.99), Product(name='Smartphone', price=699.99), Product(name='Laptop', price=999.99)]

Conclusion

The sorted function in Kotlin is a convenient method for sorting elements in an array. It ensures that the elements are ordered in ascending order by default, and additional functions like sortedBy and sortedWith allow for custom sorting criteria. 

By understanding and using this function, you can effectively manage data ordering in your Kotlin applications.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare