Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an arrayList with multiple objects

I made a list of Animals as follows :

        ArrayList<Animal> animals = new ArrayList<Animal>();
        animals.add(new Animal(1, "animal1", 50, "10 Janvier 2016", "Noir", 4, true));
        animals.add(new Animal(2, "animal2", 50, "10 Janvier 2016", "Noir", 4, true));
        animals.add(new Animal(3, "animal3", 50, "10 Janvier 2016", "Noir", 4, true));
        animals.add(new Animal(4, "animal4", 50, "10 Janvier 2016", "Noir", 4, true));
        animals.add(new Animal(5, "animal5", 50, "10 Janvier 2016", "Noir", 4, true));

I want to sort my list of animals in ArrayList by their ID. From what i've seen i have to use a comparator.

This is what i created so far...

public class ComparatorAnimal implements Comparator<Animal> {

    public int compare(Animal animals.get(0), Animal animals.get(1) {
        return animals.get(0).idAnimal - animals.get(1).idAnimal;
    }
like image 441
Aod Ren Avatar asked Dec 24 '22 10:12

Aod Ren


1 Answers

public class ComparatorAnimal implements Comparator<Animal> {

public int compare(Animal animals.get(0), Animal animals.get(1) {
    return animals.get(0).idAnimal - animals.get(1).idAnimal;
}

The method signature is wrong: you are not comparing two lists of Animal but two Animal object. Then you are comparing two id, you don't need to subtract it. Just use the same method from the Integer class.

Change your method like this:

public class ComparatorAnimal implements Comparator<Animal> {

public int compare(Animal o1, Animal o2) {
    return Integer.compare(o1.idAnimal, o2.idAnimal);
}

Now you have to use a sorted collection (like TreeMap instead of ArrayList) or invoke Collections.sort(yourList, yourComparator)

like image 122
Gianni B. Avatar answered Jan 08 '23 02:01

Gianni B.