简体   繁体   中英

Sorting an object ArrayList by an attribute value in Java

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.

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

This is old but I found it to be usefull.

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

works too.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM