13

I have ArrayList zombie, which is populated with an object called Zombie. Zombie has the attributes health, x, y. How would I sort the array in ascending order, using the attribute x of Zombie, which is set to initially have random values?

I have already found a possible solution to my problem, but I do not understand the syntax of the answer. Explaining that answer may help, also.

Community
  • 1
  • 1
user2414341
  • 135
  • 1
  • 1
  • 6

4 Answers4

31

You want to use Collections.sort in conjunction with a custom Comparator.

Collections.sort(list, new Comparator<Zombie>() {
    @Override
    public int compare(Zombie z1, Zombie z2) {
        if (z1.x() > z2.x())
            return 1;
        if (z1.x() < z2.x())
            return -1;
        return 0;
    }
});

Essentially, a Comparator is a key that signifies how a list should be ordered via its compare method. With the Comparator above, we consider z1 to be greater than z2 if z1 has the higher x value (and we show this by returning 1). Based on this, we sort list.

arshajii
  • 127,459
  • 24
  • 238
  • 287
  • Thank you for this explanation and answer, but can you go more in-depth into the meaning of everything? If you could explain each line of code to me, and explain what exactly is going on, that would be most helpful. – user2414341 May 27 '13 at 18:00
  • So incredibly ugly, but it works. This looks like the only way to do this type of sort (similar answer all over the web). – Herb Meehan Dec 26 '15 at 04:45
  • why did you use 2 ifs, and not an else-if? – orrymr Jun 09 '16 at 07:20
  • 3
    @orrymr It doesn't matter in this case because of the `return`; you could do it either way. – arshajii Jun 09 '16 at 14:09
7

using JAVA 8 do this:

zombie.sort((Zombie z1, Zombie z2) -> {
   if (z1.x() > z2.x())
     return 1;
   if (z1.x() < z2.x())
     return -1;
   return 0;
});

List interface now supports the sort method directly

patz
  • 1,306
  • 4
  • 25
  • 42
0

This is old but I found it to be usefull.

zombie.sort((Zombie z1,Zombie z2) -> (Integer.compare(z1.x(),z2.x())));

works too.

Syrin
  • 1
  • 1
0

Java-8 solution using Stream API:

List<Zombie> sorted = zombie.stream()
                            .sorted(Comparator.comparing(Zombie::getX))
                            .collect(Collectors.toList());

If x is of type int, the idiomatic way is to use Comparator.comparingInt.

List<Zombie> sorted = zombie.stream()
                            .sorted(Comparator.comparingInt(Zombie::getX))
                            .collect(Collectors.toList());

If you want to sort the original list, zombie itself:

zombie.sort(Comparator.comparing(Zombie::getX));

If x is of type int, the idiomatic way is to use Comparator.comparingInt.

zombie.sort(Comparator.comparingInt(Zombie::getX));
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110