Sort collection by multiple fields in Kotlin


A Collection is an object where developers can group different types of related objects in one place. There are different kinds of collections present in Kotlin library such as List, Array, etc.

In this article, we will see how we can sort a collection by different properties present inside that collection. In order to do that, we will be taking the help of the following two functions provided by the Kotlin library.

  • sortedWith()

  • compareBy()

sortedWith()

sortedWith() is a function provided by the Kotlin library that returns a list of all the elements sorted by a specified comparator. According to official Kotlin documentation, the function definition is,

fun <T> Array<out T>.sortedWith(
   comparator: Comparator<in T>
): List<T>

sortedWith() takes a comparator as an argument and compares the custom properties of each object and sorts the same.

compareBy()

compareBy() is responsible for creating the comparator that we will pass to sortedWith() in order to sort the object properties. As per the Kotlin documentation, the function definition goes like this:

fun <T> compareBy(
   vararg selectors: (T) -> Comparable<*>?
): Comparator<T>

Example

In the following example, we will create a class Student that will hold different kinds of values such as student name, their age, and corresponding GPA. We want to sort the same as a whole, not by only "age" or "GPA".

fun main()
{

   val studentA=Student("Student A",18,7.0)
   val studentB=Student("Student B",18,6.9)
   val studentC=Student("Student C",20,7.3)
   val studentD=Student("Student D",22,8.3)

   val studentsList=listOf(
      studentA,
      studentB,
      studentC,
      studentD
   );

   val sortedList=studentsList.sortedWith(
      compareBy(
         {it.age},
         {it.GPA}
      )
   )

   sortedList.forEach {
      println("name: ${it.name}, age: ${it.age}, GPA: ${it.GPA}")
   }
}

class Student(val name:String, val age:Int, val GPA: Double)

Output

Once you execute the code, it will generate the following output −

name: Student B, age: 18, GPA: 6.9
name: Student A, age: 18, GPA: 7.0
name: Student C, age: 20, GPA: 7.3
name: Student D, age: 22, GPA: 8.3

Updated on: 27-Oct-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements