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!