Sorting an object ArrayList by an attribute value in Java

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.


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