Since Date
implements Comparable
, it has a compareTo
method just like String
does.
(由于Date
实现Comparable
,因此它具有String
一样的compareTo
方法。)
So your custom Comparator
could look like this:
(因此,您的自定义Comparator
可能如下所示:)
public class CustomComparator implements Comparator<MyObject> {
@Override
public int compare(MyObject o1, MyObject o2) {
return o1.getStartDate().compareTo(o2.getStartDate());
}
}
The compare()
method must return an int
, so you couldn't directly return a boolean
like you were planning to anyway.
(compare()
方法必须返回一个int
,因此无论如何您都不能直接返回一个boolean
。)
Your sorting code would be just about like you wrote:
(您的排序代码几乎就像您写的那样:)
Collections.sort(Database.arrayList, new CustomComparator());
A slightly shorter way to write all this, if you don't need to reuse your comparator, is to write it as an inline anonymous class:
(如果您不需要重用比较器,则编写所有这些内容的一种更短的方法是将其编写为内联匿名类:)
Collections.sort(Database.arrayList, new Comparator<MyObject>() {
@Override
public int compare(MyObject o1, MyObject o2) {
return o1.getStartDate().compareTo(o2.getStartDate());
}
});
You can now write the last example in a shorter form by using a lambda expression for the Comparator
:
(现在,您可以通过对Comparator
使用lambda表达式 ,以较短的形式编写最后一个示例:)
Collections.sort(Database.arrayList,
(o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));
And List
has a sort(Comparator)
method, so you can shorten this even further:
(而且List
具有sort(Comparator)
方法,因此您可以进一步缩短它:)
Database.arrayList.sort((o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));
This is such a common idiom that there's a built-in method to generate a Comparator
for a class with a Comparable
key:
(这是一个非常常见的习惯用法,因此有一个内置方法可以为具有Comparable
键的类生成Comparator
:)
Database.arrayList.sort(Comparator.comparing(MyObject::getStartDate));
All of these are equivalent forms.
(所有这些都是等效形式。)