0

I have a list of Animals where there are 3 types TIGER, DOG, ANT, they also have a field that determines the order that needs 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 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, it 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.

Pankaj Lilan
  • 4,245
  • 1
  • 29
  • 48
Kenenisa Bekele
  • 835
  • 13
  • 34
  • Possible duplicate of [How to use Collections.sort() in JAVA ? (Specific situation)](http://stackoverflow.com/questions/16425127/how-to-use-collections-sort-in-java-specific-situation) – Issam T. Feb 05 '17 at 16:16
  • 1
    Question isn't Android specific enough, consider using the Java tag instead – OneCricketeer Feb 05 '17 at 16:52

2 Answers2

1

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.

Jemar Jones
  • 1,491
  • 2
  • 21
  • 27
0

Try defining a comparator to the Collections.sort() method or make the animal class implement the Comparable interface and override the compareTo(Animal animal) method and you should be good to Go .

Méhdi Màick
  • 157
  • 3
  • 7