How to Sort ArrayList of Custom Objects By Property in Kotlin Program ?

  Kotlin Interview Q&A

In this article you will learn today how to sort an array list of custom objects by the property given in Kotlin.

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) {
}
Result
A
Aa
B
X
Z

LEAVE A COMMENT