名为MyCustomClass
的自定义类具有joda LocalDateTime
的属性。我需要创建一个java.util.Comparator
类来比较MyCustomClass
的{{1}}属性的实例,其类型为TimeStamp
。我已经阅读了几篇关于此的帖子(包括this one),我已经尝试了所有方法,但答案中显示的方法似乎都不起作用。例如,以下几种方法会抛出编译错误:
LocalDateTime
我打算在代码中的其他地方使用它:
import java.time.temporal.ChronoUnit;
import java.util.Comparator;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.joda.time.Period;
import my.app.model.MyCustomClass;
public class MyCustomClassComparator implements Comparator<MyCustomClass>{
public int compare(MyCustomClass mcc1, MyCustomClass mcc2) {
//this first attempt throws a return type error for the method.
return Period.fieldDifference(mcc2.getTimestamp(), mcc1.getTimestamp());
//This next attempt says that LocalDateTimes are not valid arguments
Duration.between(mcc2.getTimestamp(), mcc1.getTimestamp());
//The next approach also says LocalDateTimes are not valid arguments.
DateTime.parse(mcc2.getTimestamp()), mcc1.getTimestamp()).getSeconds();
//This boilerplate approach says the minus sign is not valid for LocalDateTime
return mcc1.getTimestamp() - mcc2.getTimestamp();
}
}
如何根据Joda List<MyCustomClass> mccs = new ArrayList<MyCustomClass>();
// Sort by time stamp:
Collections.sort(mccs, new MyCustomClassComparator());
属性编写Comparator
类来比较MyCustomClass
的实例?
答案 0 :(得分:3)
LocalDateTime实现了comparable接口,因此您可以实现比较符:
public class MyCustomClassComparator implements Comparator<MyCustomClass> {
@Override
public int compare(final MyCustomClass mcc1, final MyCustomClass mcc2) {
return mcc1.getTimestamp().compareTo(mcc2.getTimestamp());
}
}
答案 1 :(得分:3)
如果您需要的只是一个比较器实例:
类似于Iłya Bursov的答案,因为LocalDateTime实现了可比性,所以您可以使用Comparator.comparing
Comparator.comparing(MyCustomClass::getTimestamp)