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.

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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.
So incredibly ugly, but it works. This looks like the only way to do this type of sort (similar answer all over the web).
why did you use 2 ifs, and not an else-if?
@orrymr It doesn't matter in this case because of the return; you could do it either way.
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

Comments

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.

Comments

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.