[英]Sorting a List of Objects by specific value
I want to sort a List of Objects (Remarks) by a value contained in another object (DefectClass). 我想按另一个对象(DefectClass)中包含的值对对象列表(备注)进行排序。
public class Remark {
private int remarkId;
private DefectClass defectClass;
}
I have a List of Remarks and I'm using this code to sort them by the title of the defectClass : 我有一个备注列表,并且我正在使用此代码按DefenderClass的标题对它们进行排序:
Collections.sort(remarks, new Comparator<Remark>()
{
@Override
public int compare(Remark arg0, Remark arg1) {
return arg0.getDefectClass().compareTo(arg1.getDefectClass());
}
});
and this is the Compare to methode in my DefectClass model : 这是我的DefectClass模型中的Compare to methode:
public class DefectClass implements Comparable<DefectClass> {
private String DefectClassTitle;
/* Getters And Setters */
@Override
public int compareTo(DefectClass o) {
if(o.getDefectClassTitle().equals(this.getDefectClassTitle()))
return 0;
else
return 1;
}
by these codes I want to sort a List of remarks by the Title of the DefectClass of these Remarks ... but At the end I always get the same list with no sorting. 通过这些代码,我想按这些备注的DefectClass的标题对备注列表进行排序...但是最后,我总是得到相同的列表而没有排序。 What I'm doing wrong ?
我做错了什么?
The implementation of the DefectClass.compareTo()
method is incorrect, as it should compare the 2 objects and return whether the first one is lower (-1), equal(0) or greater (1) to the second one (and not only indicate whether they're equal as in your case). DefectClass.compareTo()
方法的实现是不正确的,因为它应该比较两个对象并返回第一个对象是否比第二个对象低(-1),等于(0)或更大(1)(并且不仅指出它们是否与您的情况相同)。 Assuming getDefectClassTitle()
is returning String
I'd implement the method as: 假设
getDefectClassTitle()
返回String
我将实现该方法为:
public int compareTo(DefectClass o) {
return o.getDefectClassTitle().compareTo(this.getDefectClassTitle());
}
You need not even implement Comparable
, as you are providing your own Comparator
. 您甚至不需要实现
Comparable
,因为您将提供自己的Comparator
。
Use it as follows: 如下使用它:
Collections.sort(remarks, (r1, r2) -> r1.getDefectClass().getDefectClassTitle().compareTo(r2.getDefectClass().getDefectClassTitle()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.