Kotlin Sequence sortedWith Function

The sortedWith function in Kotlin is used to sort the elements in a sequence based on a specified comparator. It is part of the Kotlin standard library and allows you to define custom sorting logic for the elements in a sequence.

Table of Contents

  1. Introduction
  2. sortedWith Function Syntax
  3. Understanding sortedWith
  4. Examples
    • Basic Usage
    • Sorting Strings by Custom Comparator
    • Using sortedWith with Custom Objects
    • Chaining sortedWith with Other Functions
  5. Real-World Use Case
  6. Conclusion

Introduction

The sortedWith function allows you to sort the elements of a sequence using a custom comparator. This is useful for scenarios where you need to apply complex or specific sorting rules to the elements in a sequence.

sortedWith Function Syntax

The syntax for the sortedWith function is as follows:

fun <T> Sequence<T>.sortedWith(comparator: Comparator<in T>): Sequence<T>

Parameters:

  • comparator: A comparator that defines the custom sorting logic for the elements.

Returns:

  • A sequence with the elements sorted according to the specified comparator.

Understanding sortedWith

The sortedWith function takes a sequence and sorts its elements using the provided comparator. This operation is terminal, meaning it triggers the evaluation of the sequence and produces a sorted sequence.

Examples

Basic Usage

To demonstrate the basic usage of sortedWith, we will create a sequence of integers and sort them using a custom comparator.

Example

fun main() {
    val numbers = sequenceOf(5, 3, 1, 4, 2)
    val comparator = compareByDescending<Int> { it }
    val sortedNumbers = numbers.sortedWith(comparator)
    println(sortedNumbers.toList()) // Output: [5, 4, 3, 2, 1]
}

Output:

[5, 4, 3, 2, 1]

Sorting Strings by Custom Comparator

This example shows how to sort a sequence of strings using a custom comparator that sorts strings by their length in ascending order.

Example

fun main() {
    val names = sequenceOf("Arjun", "Bhaskar", "Chitra", "Deepak", "Esha")
    val comparator = compareBy<String> { it.length }
    val sortedNames = names.sortedWith(comparator)
    println(sortedNames.toList()) // Output: [Esha, Arjun, Chitra, Bhaskar, Deepak]
}

Output:

[Esha, Arjun, Chitra, Bhaskar, Deepak]

Using sortedWith with Custom Objects

You can use the sortedWith function to sort custom objects based on multiple properties using a custom comparator.

Example

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

fun main() {
    val people = sequenceOf(
        Person("Arjun", 25),
        Person("Bhaskar", 30),
        Person("Chitra", 22),
        Person("Deepak", 28),
        Person("Esha", 26)
    )
    val comparator = compareBy<Person> { it.age }.thenBy { it.name }
    val sortedPeople = people.sortedWith(comparator)
    println(sortedPeople.toList()) // Output: [Person(name=Chitra, age=22), Person(name=Arjun, age=25), Person(name=Esha, age=26), Person(name=Deepak, age=28), Person(name=Bhaskar, age=30)]
}

Output:

[Person(name=Chitra, age=22), Person(name=Arjun, age=25), Person(name=Esha, age=26), Person(name=Deepak, age=28), Person(name=Bhaskar, age=30)]

Chaining sortedWith with Other Functions

The sortedWith function can be chained with other sequence functions to perform complex operations and sorting.

Example

fun main() {
    val numbers = sequenceOf(5, 3, 1, 4, 2)
    val comparator = compareByDescending<Int> { it }
    val result = numbers.filter { it % 2 == 0 }
                        .sortedWith(comparator)
                        .map { it * 2 }
    println(result.toList()) // Output: [8, 4]
}

Output:

[8, 4]

Real-World Use Case

Sorting Products by Multiple Criteria

In real-world applications, the sortedWith function can be used to sort products by multiple criteria, such as price and name.

Example

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

fun main() {
    val products = sequenceOf(
        Product("Laptop", 999.99),
        Product("Smartphone", 499.99),
        Product("Tablet", 299.99),
        Product("Smartwatch", 199.99)
    )

    val comparator = compareBy<Product> { it.price }.thenBy { it.name }
    val sortedProducts = products.sortedWith(comparator)
    println(sortedProducts.toList()) // Output: [Product(name=Smartwatch, price=199.99), Product(name=Tablet, price=299.99), Product(name=Smartphone, price=499.99), Product(name=Laptop, price=999.99)]
}

Output:

[Product(name=Smartwatch, price=199.99), Product(name=Tablet, price=299.99), Product(name=Smartphone, price=499.99), Product(name=Laptop, price=999.99)]

Conclusion

The sortedWith function in Kotlin provides used for sorting elements in a sequence using custom comparators. By understanding and using the sortedWith function, you can efficiently organize data in your Kotlin applications, making them more flexible and responsive to user needs.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top