Quantcast
Channel: How to sort List of objects by some property - Stack Overflow
Viewing all articles
Browse latest Browse all 19

Answer by Frank Kevy for How to sort List of objects by some property

$
0
0

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]

Viewing all articles
Browse latest Browse all 19

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>