Kotlin Program to Sort ArrayList of Custom Objects By Property

1. Introduction


In this tutorial, you will learn how to sort the ArrayList of Custom objects and sort by their given property or field.

This is part of the Kotlin Programming Series.

First, We will see the example program to sort the custom class and next, how to sort the List of Employee objects.

Kotlin Program to Sort ArrayList of Custom Objects By Property



2. Kotlin Example to Sort ArrayList of Custom Objects by Property - CustomObj Class



package com.javaprogramto.kotlin.list.sort.custom

fun main() {

var customObjList = ArrayList<CustomObj>();
customObjList.add(CustomObj("yahoo"))
customObjList.add(CustomObj("apple"))
customObjList.add(CustomObj("google"))
customObjList.add(CustomObj("bing"))

println("Before sorting : $customObjList")
var sortedList = customObjList.sortedWith(compareBy({it.customObjPropery}));

println("After sorting : $sortedList")
}

public class CustomObj(var customObjPropery : String){

override fun toString(): String {
return "$customObjPropery" }
}

Output;

[Before sorting : [yahoo, apple, google, bing]
After sorting : [apple, bing, google, yahoo]]

In the above code, the First created a list of CustomObj objects. Kotlin collection api is provided with sortedWith() and compareBy() methods.

Simple words, First call Lists sortedWith() method and it takes Comparator's compareBy() method that takes the property for sorting.

3. Kotlin Example to Sort ArrayList of Custom Objects by Property - Sort Employee by Id


package com.javaprogramto.kotlin.list.sort.custom

fun main() {

var employeeObjList = ArrayList<Employee>();
employeeObjList.add(Employee(500))
employeeObjList.add(Employee(300))
employeeObjList.add(Employee(100))
employeeObjList.add(Employee(200))

println("Employee Objects Before sorting : $employeeObjList")
var sortedEmpList = employeeObjList.sortedWith(compareBy({it.id}));

println("Employee Objects After sorting : $sortedEmpList")
}

public class Employee(var id : Int){

override fun toString(): String {
return "$id" }
}

Output:


[Employee Objects Before sorting : [500, 300, 100, 200]
Employee Objects After sorting : [100, 200, 300, 500]]

In the above code, Sorting List of Employees by id property. 

Almost same as the above section using list.sortedWith() and Comparators compareBy() method.

4. Conclusion


In conclusion, You've seen how to sort the list of custom objects upon a particular property.

Above discussed examples are shown for CustomObj class and Employee class sorting by its properties.

All the code is shown in this article is over GitHub.

You can download the project directly and can run in your local without any errors.



If you have any queries please post in the comment section.

Sort ArrayList of Custom Objects By Property

0 Comments