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

Answer by Jagadeesh for How to sort List of objects by some property

$
0
0

We can sort the list in one of two ways:

1. Using Comparator : When required to use the sort logic in multiple placesIf you want to use the sorting logic in a single place, then you can write an anonymous inner class as follows, or else extract the comparator and use it in multiple places

  Collections.sort(arrayList, new Comparator<ActiveAlarm>() {        public int compare(ActiveAlarm o1, ActiveAlarm o2) {            //Sorts by 'TimeStarted' property            return o1.getTimeStarted()<o2.getTimeStarted()?-1:o1.getTimeStarted()>o2.getTimeStarted()?1:doSecodaryOrderSort(o1,o2);        }        //If 'TimeStarted' property is equal sorts by 'TimeEnded' property        public int doSecodaryOrderSort(ActiveAlarm o1,ActiveAlarm o2) {            return o1.getTimeEnded()<o2.getTimeEnded()?-1:o1.getTimeEnded()>o2.getTimeEnded()?1:0;        }    });

We can have null check for the properties, if we could have used 'Long' instead of 'long'.

2. Using Comparable(natural ordering): If sort algorithm always stick to one property:write a class that implements 'Comparable' and override 'compareTo' method as defined below

class ActiveAlarm implements Comparable<ActiveAlarm>{public long timeStarted;public long timeEnded;private String name = "";private String description = "";private String event;private boolean live = false;public ActiveAlarm(long timeStarted,long timeEnded) {    this.timeStarted=timeStarted;    this.timeEnded=timeEnded;}public long getTimeStarted() {    return timeStarted;}public long getTimeEnded() {    return timeEnded;}public int compareTo(ActiveAlarm o) {    return timeStarted<o.getTimeStarted()?-1:timeStarted>o.getTimeStarted()?1:doSecodaryOrderSort(o);}public int doSecodaryOrderSort(ActiveAlarm o) {    return timeEnded<o.getTimeEnded()?-1:timeEnded>o.getTimeEnded()?1:0;}

}

call sort method to sort based on natural ordering

Collections.sort(list);

Viewing all articles
Browse latest Browse all 19

Trending Articles



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