Kotlin Array sortedBy Function

The sortedBy 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. sortedBy Function Syntax
  3. Understanding sortedBy
  4. Examples
    • Basic Usage
    • Using sortedBy with Custom Types
    • Sorting with Multiple Criteria
  5. Real-World Use Case
  6. Conclusion

Introduction

The sortedBy function returns a list containing all elements of the original array sorted according to the value returned by the specified selector function. It is a simple and effective way to sort arrays based on custom criteria.

sortedBy Function Syntax

The syntax for the sortedBy function is as follows:

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

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:

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

Understanding sortedBy

The sortedBy 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 sortedBy, 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)
    val sortedByAbsoluteValue = numbers.sortedBy { it.absoluteValue }
    println("Sorted by absolute value: $sortedByAbsoluteValue")
}

Output:

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

Using sortedBy with Custom Types

This example shows how to use sortedBy 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)
    )

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

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 sortedBy in combination with sortedWith 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)
    )

    val sortedByNameThenAge = people.sortedWith(compareBy<Person> { it.name }.thenBy { it.age })
    println("Sorted people by name and then by age: $sortedByNameThenAge")
}

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

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

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 sortedBy function in Kotlin is used for sorting elements in an array based on a specified property or condition. It allows you to create a sorted list 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

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