🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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
- Introduction
sortedByFunction Syntax- Understanding
sortedBy - Examples
- Basic Usage
- Using
sortedBywith Custom Types - Sorting with Multiple Criteria
- Real-World Use Case
- 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 typeTand returns a value of typeRthat 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.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment