Sort in java using the comparator

advertisements

I am trying to sort set using Comparator as shown below.

Set seatSet = tc.getTheatreSeat();
    List listArr = new ArrayList(seatSet);
    Collections.sort(listArr, new Comparator() {
        public int compare(Object arg0, Object arg1) {
            TheatreSeat r1 = (TheatreSeat) arg0;
            TheatreSeat r2 = (TheatreSeat) arg1;
            if (r2.getId() < r1.getId()) {
                return 1;
            }
            return 0;
        }
    });

But its not working. whats wrong with my code please help.


The return value for a compare function should be -1, 0 or +1, not just 1 or 0.

return Integer.compare(r1.getId(), r2.getId());

in place of the if statement should do the job.

A Java 8 sort using a lambda would be

listArr.sort(Comparator.comparing(e -> e.getId()));