We can use the Comparator.comparing()
method to sort a list based on an object's property.
class SortTest{ public static void main(String[] args) { ArrayList<ActiveAlarm> activeAlarms = new ArrayList<>(){{ add(new ActiveAlarm("Alarm 1", 5, 10)); add(new ActiveAlarm("Alarm 2", 2, 12)); add(new ActiveAlarm("Alarm 3", 0, 8)); }}; /* I sort the arraylist here using the getter methods */ activeAlarms.sort(Comparator.comparing(ActiveAlarm::getTimeStarted) .thenComparing(ActiveAlarm::getTimeEnded)); System.out.println(activeAlarms); }}
Note that before doing it, you'll have to define at least the getter methods of the properties you want to base your sort on.
public class ActiveAlarm { public long timeStarted; public long timeEnded; private String name = ""; private String description = ""; private String event; private boolean live = false; public ActiveAlarm(String name, long timeStarted, long timeEnded) { this.name = name; this.timeStarted = timeStarted; this.timeEnded = timeEnded; } public long getTimeStarted() { return timeStarted; } public long getTimeEnded() { return timeEnded; } @Override public String toString() { return name; }}
Output:
[Alarm 3, Alarm 2, Alarm 1]