Home > Java > javaTutorial > body text

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

Patricia Arquette
Release: 2024-11-20 16:23:13
Original
305 people have browsed it

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
}
Copy after login

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);
Copy after login

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;
    };
Copy after login

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;
    }
};
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template