日期排序 - 从最新到最旧
Collections.sort(someList, new Comparator<SomeObject>() {
public int compare(final SomeObject object1, final SomeObject object2) {
return (object1.getSomeDate()).compareTo(object2.getSomeDate());
}}
);
它会给我具有最新日期的对象,这意味着列表将包含具有最新日期到最旧日期的对象集吗?
Collections.sort(someList, new Comparator<SomeObject>() {
public int compare(final SomeObject object1, final SomeObject object2) {
return (object1.getSomeDate()).compareTo(object2.getSomeDate());
}}
);
Would it give me the objects with latest dates meaning the list will contain the set of objects with latest date to oldest date?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
Comparator.comparing
您可以传递方法引用< /a> 到
比较器.比较
。如果您希望对象根据日期按升序排序:
或
按降序排序。
Comparator.comparing
You can pass a method reference to
Comparator.comparing
.If you want the objects to be sorted in ascending order based on the date:
or
for descending order.
确保您可以使用:
To be sure you can use:
Date
的默认排序会将较新的日期放在较旧的日期之后,因此最旧的日期将位于列表的开头,而最新的日期将位于列表的末尾。在我看来,比较器
一直很难阅读,所以我转而使用谷歌的Ordering
实现Comparator
的对象更加简洁。例如,您的Comparator
可以这样写:此代码创建的顺序 Comparator 将使用
Date
根据 SomeObject 对象的Date
对它们进行排序。的自然排序。但是,Ordering
真正的好处是,一些额外的方法可以更改顺序,而无需编写更多逻辑,例如,要将日期顺序反转为最新到最旧,您只需添加一个调用撤销():The default ordering of
Date
will put newer dates after older dates so the oldest dates would be at the beginning of your list and the newest dates at the end.Comparators
have always been hard to read in my opinion so I have switched to using google'sOrdering
objects that implementComparator
a little cleaner. For example yourComparator
could be written like this:The order Comparator that this code created would sort SomeObject objects based on their
Date
using theDate
's natural ordering. But what makesOrdering
really nice is some of extra methods change the order without having to write any more logic, for example to reverse the order of dates to be newest to oldest you just have to add a call to reverse():这是旧的,但可能有人可以使用它。可以使用java8进行排序,如下所示:
This is old but may be someone can use it. It may be sorted using java8 as follows:
通过使用 lambdaj 您可以通过更简单、更易读的方式获得相同的结果,如下所示:
比编写一个不起眼的内部类要好得多,不是吗?
By using lambdaj you could achieve the same result in an easier and more readable way as it follows:
Far better than writing an obscure inner class, isn't it?
试试这个:
Date.getTime() 将日期“转换”为 long,这样更容易比较和排序。
无论如何,在幕后 Long 与此进行比较:
如果你想反转排序,只需乘以 -1 即可,如下所示:
Try this:
Date.getTime() "converts" the date to a long, which is easier to compare and sort.
Anyway behind the curtain Longs are compared with this:
If you want to invert the sort, just multiply by -1 like this: