English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin program sorts an ArrayList of custom objects by property

Comprehensive Collection of Kotlin Examples

In this program, you will learn how to sort an ArrayList of custom objects by a given property in Kotlin.

Example: Sort an 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 running the program, the output is:

A
Aa
B
X
Z

In the above program, we define a CustomObject class with a string property customProperty.

In the main() method, we create an array list of custom objects list and use5objects were initialized.

To sort the list by property, we use the list's sortedWith() method. The sortedWith() method takes a comparator compareBy, which compares each object of customProperty and sorts it.

Then store the sorted list in the variable sortedList.

The following is the equivalent Java code:Java Program to Sort Custom Objects in ArrayList by Property.

Comprehensive Collection of Kotlin Examples