Sorting Arrays of Objects
You can use the sortBy() method in conjunction with a custom comparison function that takes an object’s key and uses it to sort arrays of custom objects.
Below is the Scala program to implement the approach:
case class Person(name: String, age: Int)
val people = Array(Person("Alice", 25), Person("Bob", 30), Person("Charlie", 20))
val sortedPeople = people.sortBy(_.age) // Sort by age
println(sortedPeople.mkString(", ")) // Output: Person(Charlie,20), Person(Alice,25), Person(Bob,30)
Output:
How to Sort an Array in Scala?
Sorting arrays effectively is essential for many applications, regardless of whether you’re working with texts, custom objects, or numerical data. Because Scala is a strong and expressive language, it provides a variety of array sorting methods that may be customized to fit various needs and situations.
This article will examine the nuances of sorting arrays in Scala and the different approaches and techniques used to do this task successfully.
Table of Content
- What is Sorting in an Array?
- Using ‘sortWith’ Method
- Using ‘sorted()’ Method
- Using ‘sortBy()’ Method
- Sorting Arrays of Objects
- Sorting Arrays in Reverse Order
- Conclusion
- FAQs
Contact Us