0

I have a list of dogs with their name, breed, age, weight and tail length. I have already sorted the list by tail length and am now supposed to sort the dogs that have the same tail length by their name. For example this is how the list should look like:

Charlie  Golden   2years 3kg 2.0cm

Bob      Bulldog  3years 4kg 3.3cm

Lucy     Golden   4years 3kg 3.3cm 

Molly    Bulldog  5years 7kg 5.2cm

I have a method called sortTail() that sorts by tail length and a method sortName() that sorts by name.

sortTail()

ArrayList<Dog> dogs = new ArrayList<>();

sortName()

What should I do in between to only sort the ones with the same tail length?

2 Answers 2

2

If your Dog instances are in a List your best bet for sorting is using Java's Comparator class with List#sort. You can use the default methods of Comparator to create a comparator on multiple criteria. For example, the following code will sort dogs by tail length, then by name for those that have the same tail length:

List<Dog> dogs = // ...
dogs.sort(
    Comparator.comparing(Dog::getTailLength)
              .thenComparing(Dog::getName));
Sign up to request clarification or add additional context in comments.

Comments

0

Just in case you want to implement your own comparator or your task requires that. However, SDJ's answer should be preferred over inventing of bicycle:

Comparator<Dog> dogComparator = 
    (a,b) -> {
        if (a.getTailLength() == b.getTailLength()) 
            return a.getName().compareTo(b.getName());
        else 
            return 0;
    }


Collections.sort(dogs, dogComparator);

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.