Kotlin Array sortBy Function

The sortBy function in Kotlin is used to sort elements in an array based on a specified selector function. This function is part of the Kotlin standard library and provides a way to sort arrays according to a custom property or condition.

Table of Contents

  1. Introduction
  2. sortBy Function Syntax
  3. Understanding sortBy
  4. Examples
    • Basic Usage
    • Using sortBy with Custom Types
    • Sorting with Multiple Criteria
  5. Real-World Use Case
  6. Conclusion

Introduction

The sortBy function sorts the elements of an array in-place according to the value returned by the specified selector function. It is a simple and effective way to sort arrays based on custom criteria.

sortBy Function Syntax

The syntax for the sortBy function is as follows:

inline fun <T, R : Comparable<R>> Array<out T>.sortBy(selector: (T) -> R?): Unit

Parameters:

  • selector: A lambda function that takes an element of type T and returns a value of type R that is used for sorting.

Returns:

  • This function does not return a value.

Understanding sortBy

The sortBy function is used to sort elements in an array based on the value returned by the selector function. This is particularly useful for sorting custom objects or when sorting based on specific properties of the elements.

Examples

Basic Usage

To demonstrate the basic usage of sortBy, we will create an array of integers and sort them by their absolute values.

Example

fun main() {
    val numbers = arrayOf(-3, 2, -1, 4, -5)
    numbers.sortBy { it.absoluteValue }
    println("Sorted by absolute value: ${numbers.joinToString()}")
}

Output:

Sorted by absolute value: -1, 2, -3, 4, -5

Using sortBy with Custom Types

This example shows how to use sortBy to sort an array of custom objects based on a specific property.

Example

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

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

    people.sortBy { it.age }
    println("Sorted people by age: ${people.joinToString()}")
}

Output:

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

Sorting with Multiple Criteria

This example demonstrates how to use sortBy in combination with sortWith to sort an array based on multiple criteria.

Example

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

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

    people.sortWith(compareBy<Person> { it.name }.thenBy { it.age })
    println("Sorted people by name and then by age: ${people.joinToString()}")
}

Output:

Sorted people by name and then by age: [Person(name='Anjali', age=30, height=5.5), Person(name='Priya', age=22, height=5.6), Person(name='Ravi', age=22, height=5.7), Person(name='Ravi', age=25, height=5.8)]

Real-World Use Case

Sorting Products by Price

In real-world applications, the sortBy function can be used to sort data objects based on various properties, such as sorting a list of products by price.

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)
    )

    products.sortBy { it.price }
    println("Products sorted by price: ${products.joinToString()}")
}

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 sortBy function in Kotlin is used for sorting elements in an array based on a specified property or condition. It allows you to sort elements in-place based on custom criteria, making it useful for sorting custom objects and data. By understanding and using this function, you can effectively manage data sorting in your Kotlin applications.

Comments