Reputation: 1
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?
Upvotes: 0
Views: 144
Reputation:
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));
Upvotes: 2
Reputation: 3236
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);
Upvotes: 0