Sorting List of Objects Based on Property
You have a custom Java class ActiveAlarm that contains properties related to alarms, including timeStarted and timeEnded. You need to sort a List
Solution: Using Comparator
In Java, you can sort objects using a Comparator. A comparator is an interface that represents a function to compare two objects. You can create a custom comparator to compare ActiveAlarm objects based on the specified criteria.
Here's an example implementation using a comparator:
import java.util.Collections; import java.util.Comparator; class ActiveAlarm { public long timeStarted; public long timeEnded; // Other properties and accessor methods... } public class SortingAlarms { public static void main(String[] args) { List<ActiveAlarm> alarms = new ArrayList<>(); // Add alarms to the list // Create a comparator to sort by timeStarted and then timeEnded 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; } }; Collections.sort(alarms, comparator); // Print the sorted list for (ActiveAlarm alarm : alarms) { System.out.println(alarm.timeStarted + " - " + alarm.timeEnded); } } }
This comparator first compares the timeStarted values of the alarms, and if those are equal, it compares the timeEnded values. The result of the comparison (1, 0, or -1) is used to determine the sorting order.
Note: For Java 8 and later, you can use lambda expressions to simplify the implementation of the comparator:
Collections.sort(alarms, (a1, a2) -> Long.compare(a1.timeStarted, a2.timeStarted) != 0 ? Long.compare(a1.timeStarted, a2.timeStarted) : Long.compare(a1.timeEnded, a2.timeEnded));
The above is the detailed content of How to Sort a List of Java Objects Based on Multiple Properties?. For more information, please follow other related articles on the PHP Chinese website!