[英]How to sort a list using comparator in Descending order (based on salary which is a long value)
[英]how to sort date in descending order using comparator
我有一个带有getter setter和testBean
的bean对象testBean
。我正在从数据库中检索结果并将其存储在TreeMap
Map
的输出将如下所示:
{Student1 = [testBean[Dept=Science,ID=12,grade=A,Date=12-Jan-2013]]
[testBean[Dept=Science,ID=12,grade=B,Date=14-Mar-2013]]
{Student2 = [testBean[Dept=Science,ID=02,grade=A,Date=12-Jan-2013]]
[testBean[Dept=Science,ID=02,grade=A,Date=14-Mar-2013]]
我需要按降序排列输出,以便最新的日期出现。 所以我使用比较器来对日期进行排序:
public int DateCompare(Object studentObj, Object anotherStudentObj) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
String value = ((testBean) studentObj).getDateTmTrans();
String value1 = ((testBean) anotherStudentObj).getDateTmTrans();
int retVal = 0;
try {
Date firstDate = dateFormat.parse(value);
Date secondDate = dateFormat.parse(value1);
retVal = firstDate.compareTo(secondDate);
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
但我无法按降序排列日期。 是否有任何解决方案可以获得所需的输出?
欢迎任何建议
提前致谢
但我无法按降序排列日期。
两个简单的选择:
secondDate.compareTo(firstDate)
反转您的比较。 (我假设在您的真实代码中,您实际上正在返回retVal
;它会在您发布的代码中被忽略。) Collections.reverseOrder(Comparator)
创建一个比较原始逆序的比较器。 相反,比较firstDate
对secondDate
,比较secondDate
对firstDate
:
retVal = secondDate.compareTo(firstDate);
并且不要忘记返回retVal
而不是0
;)
你可以在比较器的构造函数中添加一个布尔参数,例如boolean descending
,然后执行以下操作:
retVal = (descending ? -1 : 1) * firstDate.compareTo(secondDate);
在这里,如果您通过将true作为“降序”参数传递来创建比较器,它将翻转符号,保持0不受影响,并且实际上您最终会得到一个可轻松配置的比较器,以帮助您按升序/降序排序日期订购。
你可以试试这个:
static final Comparator<All_Request_data_dto> byDate
= new Comparator<All_Request_data_dto>() {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
public int compare(All_Request_data_dto ord1, All_Request_data_dto ord2) {
Date d1 = null;
Date d2 = null;
try {
d1 = sdf.parse(ord1.lastModifiedDate);
d2 = sdf.parse(ord2.lastModifiedDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (d1.getTime() > d2.getTime() ? -1 : 1); //descending
// return (d1.getTime() > d2.getTime() ? 1 : -1); //ascending
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.