Kotlin Program to Sort ArrayList of Custom Objects By Property

In this program, you'll learn to sort an arraylist of custom object by their given property in Kotlin.

Example: Sort ArrayList of Custom Objects By Property

import java.util.*

fun main(args: Array<String>) {

    val list = ArrayList<CustomObject>()
    list.add(CustomObject("Z"))
    list.add(CustomObject("A"))
    list.add(CustomObject("B"))
    list.add(CustomObject("X"))
    list.add(CustomObject("Aa"))

    var sortedList = list.sortedWith(compareBy({ it.customProperty }))

    for (obj in sortedList) {
        println(obj.customProperty)
    }
}

public class CustomObject(val customProperty: String) {
}

When you run the program, the output will be:

A
Aa
B
X
Z

In the above program, we've defined a CustomObject class with a String property, customProperty.

In the main() method, we've created an array list of custom objects list, initialized with 5 objects.

For sorting the list with the property, we use list's sortedWith() method. The sortedWith() method takes a comparator compareBy that compares customProperty of each object and sorts it.

The sorted list is then stored in the variable sortedList.

Here's the equivalent Java code: Java program to sort an ArrayList of custom objects by property.