-2

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.

earthmover
  • 4,395
  • 10
  • 43
  • 74
user3887681
  • 31
  • 1
  • 1
  • 2
  • 7
    1) Indent your code. 2) "its not working" is not a good description. 3) We don't know what kind of set you're using - most don't allow for explicit ordering. 4) Please put together a short but *complete* program demonstrating the problem. – Jon Skeet Jul 29 '14 at 12:33
  • In what way is it not working? I see you have copied the contents of the `Set` into a `List` and are trying to sort the `List`, so why did you call your post `Sort set`? – John B Jul 29 '14 at 12:35
  • set contains objects of class TheatreSeat , which has value id rownumber etc. i want to sort this with id. How can i do this> sorry for my bad attempt of posting question as am new here – user3887681 Jul 29 '14 at 12:38

2 Answers2

5

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()));
soru
  • 5,464
  • 26
  • 30
0

It looks correct enough that it should work mostly.

For understanding the int return value of a comparator defines 3 results:

  1. less then 0 (minus values) means first element is behind second
  2. zero means they are equals
  3. more then 0 (positiv values) means first element is before second

By inversing positive to negative and vice versa you can define ascending and descending order.

So here a full version of your comparator (I placed the IDs in variables to make it more simple to read):

new Comparator() {
  public int compare(Object val1, Object val2) {
    int id1 = ((TheatreSeat) val1).getId();
    int id2 = ((TheatreSeat) val2).getId();
    return id1 - id2;
  }
}

So why I write id1 - id2 ? Because it results in exactly what we want. If id2 is greater then id1 the result will be less zero and vice versa and when id1 and id2 equals the result will be zero ;)

Use a step debugger to inspect your List before sorting and after to check the result.

Rene M.
  • 2,660
  • 15
  • 24
  • 1
    just as a note, the technique of comparing by subtraction will fail for numbers large enouygh to get integer overflow. See: http://stackoverflow.com/questions/2728793/java-integer-compareto-why-use-comparison-vs-subtraction – soru Jul 29 '14 at 14:15