简体   繁体   中英

how to make list of duplicates in custom arraylist Java

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?

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));

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM