Kenenisa Bekele Kenenisa Bekele - 4 years ago 103
Android Question

Best way to sort a list using two different fields

I have a list of Animals where there are 3 types TIGER, DOG, ANT, they also have a field that determines the order that need to be sorted

public class Animal {
private final AnimalType animalType;

private final int orderNumber;


public Animal(AnimalType animalType, int orderNumber) {
this.animalType = animalType;
this.orderNumber = orderNumber;
}

public int getOrderNumber() {
return orderNumber;
}

public AnimalType getAnimalType() {
return animalType;
}
}


public enum AnimalType {
TIGER("tiger"),
DOG("dog"),
ANT("ant");}


The list needs to be sorted by putting the TIGER first then DOG then ANT, but also each Animal has a sequential order number

So if you we have this

List<Animal> animals = new ArrayList<>();

animals.add(new Animal(TIGER, 2));
animals.add(new Animal(DOG, 5));
animals.add(new Animal(ANT, 1));
animals.add(new Animal(ANT, 3));
animals.add(new Animal(TIGER, 3));
animals.add(new Animal(DOG, 4));
animals.add(new Animal(TIGER, 1));
animals.add(new Animal(DOG, 2));
animals.add(new Animal(DOG, 1));
animals.add(new Animal(ANT, 2));
animals.add(new Animal(DOG, 3));


After sorting if should be like this

new Animal(TIGER, 1);
new Animal(TIGER, 2);
new Animal(TIGER, 3);
new Animal(DOG, 1);
new Animal(DOG, 2);
new Animal(DOG, 3);
new Animal(DOG, 4);
new Animal(DOG, 5);
new Animal(ANT, 1);
new Animal(ANT, 2);
new Animal(ANT, 3);


What is the best way to sort it ?? I am using Android so it should be Java 7.

Answer Source

You can use Collections.sort, but first you need to define a comparator. In your case something like this may work:

class AnimalCompare implements Comparator<Animal> {
    @Override
    public int compare(Animal o1, Animal o2) {
        if (o1.getAnimalType().ordinal() < o2.getAnimalType().ordinal()){
            return -1;
        } else if (o1.getAnimalType().ordinal() > o2.getAnimalType().ordinal()) {
            return 1;
        }
        return o1.getOrderNumber() - o2.getOrderNumber();
    }
}

and then:

Collections.sort(animals, new AnimalCompare());

Note that this is all assuming no null values.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download