Home >Java >javaTutorial >How to Sort a List of Objects by Multiple Properties in Java?

How to Sort a List of Objects by Multiple Properties in Java?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-20 16:23:13397browse

How to Sort a List of Objects by Multiple Properties in Java?

Sorting a List of Objects by Multiple Properties in Java

In Java, sorting a list of objects by properties requires the use of comparators. Consider the following example:

public class ActiveAlarm {
    public long timeStarted;
    public long timeEnded;
    // ... other fields
}

To sort a list of ActiveAlarm objects by both timeStarted and timeEnded in ascending order, you can use a nested comparator:

List<ActiveAlarm> alarms = ...;

Comparator<ActiveAlarm> comparator =
    Comparator.comparing(alarm -> alarm.timeStarted)
              .thenComparing(alarm -> alarm.timeEnded);

Collections.sort(alarms, comparator);

Using Java 8 Lambda Expressions

Java 8 introduced lambda expressions, which provide a concise way to represent comparators:

Comparator<ActiveAlarm> comparator =
    (alarm1, alarm2) -> {
        int result = Long.compare(alarm1.timeStarted, alarm2.timeStarted);
        if (result == 0) {
            result = Long.compare(alarm1.timeEnded, alarm2.timeEnded);
        }
        return result;
    };

Alternative Sorting Method

Alternatively, you can use a custom Comparator implementation that directly accesses the properties:

Comparator<ActiveAlarm> comparator = new Comparator<ActiveAlarm>() {
    @Override
    public int compare(ActiveAlarm o1, ActiveAlarm o2) {
        int result = Long.compare(o1.timeStarted, o2.timeStarted);
        if (result == 0) {
            result = Long.compare(o1.timeEnded, o2.timeEnded);
        }
        return result;
    }
};

By using comparators, you can easily sort a list of objects by any combination of properties and in any order.

The above is the detailed content of How to Sort a List of Objects by Multiple Properties in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn