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

Java Basic Tutorial

Java flow control

Java Arrays

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (FIFO)

Java Map Collections

Java Set Collections

Java Input/Output (I/O)/O)

Java Reader/Writer

Java Other Topics

Java program to sort an ArrayList of custom objects by property

Comprehensive Java Examples

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

Example: Sort an ArrayList of custom objects by property

import java.util.*;
public class CustomObject {
    private String customProperty;
    public CustomObject(String property) {
        this.customProperty = property;
    }
    public String getCustomProperty() {
        return this.customProperty;
    }
    public static void main(String[] args) {
        ArrayList<Customobject> list = new ArrayList<>();
        list.add(new CustomObject("Z"));
        list.add(new CustomObject("A"));
        list.add(new CustomObject("B"));
        list.add(new CustomObject("X"));
        list.add(new CustomObject("Aa"));
        list.sort((o1, o2) -> o1).getCustomProperty().compareTo(o2).getCustomProperty()));
        for (CustomObject obj : list) {
            System.out.println(obj.getCustomProperty());
        }
    }
}

When running the program, the output is:

A
Aa
B
X
Z

In the above program, we defined a CustomObject class with a String attribute customProperty

We also added an initialization property constructor and a getter function getCustomProperty() that returns the customProperty

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

To sort the list by the given attribute, we use the list's sort() method. The sort() method accepts the list to be sorted (the final sorted list is also the same) and a comparator

In our example, the comparator is a lambda expression

  • from the list o1and o2to get two objects

  • use the compareTo() method to compare the customProperty of two objects

  • if o1attribute is greater than o2attribute, the last return is a positive number; if o1attribute is less than o2attribute, then the last return is a negative number; if equal, then return zero.

Based on this, the list (list) is sorted by the smallest attribute to the largest attribute and stored back into the list (list)

Comprehensive Java Examples