同时根据两个参数进行集合排序
我有一个带有两个日期字段的类,说:
class TestData {
Date activation;
Date timeStamp;
}
我想根据激活日期对上述类的列表进行排序,如果它们相等,则根据时间戳进行排序,即最大值(激活)和最大值(时间戳)。
我尝试的代码如下,仅获取 max(activation)
public class CollectionSort {
public static void main(String[] args) {
List<TestData> testList = new ArrayList<TestData>();
Collections.sort(testList, new Comparator<TestData>() {
@Override
public int compare(TestData t1, TestData t2) {
int result = 0;
if (t1.getActivation().before(t2.getActivation())) {
result = 1;
}
return result;
}
});
System.out.println("First object is " + testList.get(0));
}
}
任何帮助将不胜感激。
谢谢
I have a class with two date fields say:
class TestData {
Date activation;
Date timeStamp;
}
I want to sort the list of the above class on basis of activation
date and if they are equal then on basis of timestamp
i.e. max(activation) and max(timeStamp).
Code I tried is as follws which only fetch max(activation)
public class CollectionSort {
public static void main(String[] args) {
List<TestData> testList = new ArrayList<TestData>();
Collections.sort(testList, new Comparator<TestData>() {
@Override
public int compare(TestData t1, TestData t2) {
int result = 0;
if (t1.getActivation().before(t2.getActivation())) {
result = 1;
}
return result;
}
});
System.out.println("First object is " + testList.get(0));
}
}
Any help would be greatly appreciated.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以下是如何在纯 Java 中执行此操作:
或者使用 Guava (使用
ComparisonChain
):或者使用 Commons / Lang (使用
CompareToBuilder
) :(所有三个版本都是等效的,但纯 Java 版本是最冗长的,因此最容易出错。所有三个解决方案都假设
o1.getActivation()
和o1.getTimestamp ()
实现Comparable
)。Here's how to do it in Plain Java:
Or with Guava (using
ComparisonChain
):Or with Commons / Lang (using
CompareToBuilder
):(All three versions are equivalent, but the plain Java version is the most verbose and hence most error-prone one. All three solutions assume that both
o1.getActivation()
ando1.getTimestamp()
implementComparable
).这样就可以了。!
This would do it.!