Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort List of objects by some property

I have simple class

public class ActiveAlarm {
    public long timeStarted;
    public long timeEnded;
    private String name = "";
    private String description = "";
    private String event;
    private boolean live = false;
}

and List<ActiveAlarm> con. How to sort in ascending order by timeStarted, then by timeEnded? Can anybody help? I know in C++ with generic algorithm and overload operator <, but I am new to Java.

like image 814
Jennifer Avatar asked Sep 27 '22 05:09

Jennifer


People also ask

How do you sort a list of objects?

sort() method to sort a list of objects using some examples. By default, the sort() method sorts a given list into ascending order (or natural order). We can use Collections. reverseOrder() method, which returns a Comparator, for reverse sorting.


1 Answers

Using Comparator

For Example:

class Score {

    private String name;
    private List<Integer> scores;
    // +accessor methods
}

    Collections.sort(scores, new Comparator<Score>() {

        public int compare(Score o1, Score o2) {
            // compare two instance of `Score` and return `int` as result.
            return o2.getScores().get(0).compareTo(o1.getScores().get(0));
        }
    });

With Java 8 onwards, you can simply use lambda expression to represent Comparator instance.

Collections.sort(scores, (s1, s2) -> { /* compute and return int */ });
like image 152
jmj Avatar answered Oct 18 '22 23:10

jmj