[英]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()
的方法,它按尾长排序,还有一个sortName()
方法,它按名称排序。
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
.如果您的Dog
实例在List
,则排序的最佳选择是使用 Java 的Comparator
类和List#sort
。 You can use the default methods of Comparator
to create a comparator on multiple criteria.您可以使用Comparator
的默认方法根据多个条件创建比较器。 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:但是,SDJ 的答案应该比发明自行车更受欢迎:
Comparator<Dog> dogComparator =
(a,b) -> {
if (a.getTailLength() == b.getTailLength())
return a.getName().compareTo(b.getName());
else
return 0;
}
Collections.sort(dogs, dogComparator);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.