Kotlin Program to Sort ArrayList of Custom Objects By Property

Kotlin Program to Sort ArrayList of Custom Objects By Property. For sorting the list with the property, we use the list ‘s sorted with the () method. The sorted with() method takes a comparator to compare that compares the custom property of each object and sorts it.

Kotlin Program to Sort ArrayList of Custom Objects By Property

Source Code

import java.util.*

fun main(args: Array<String>) {

    val list = ArrayList<CustomObject>()
    list.add(CustomObject("A"))
    list.add(CustomObject("B"))
    list.add(CustomObject("C"))
    list.add(CustomObject("D"))
    list.add(CustomObject("Aa"))

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

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

public class CustomObject(val customProperty: String) {
}

Output