A custom class called MyCustomClass
has a property that it s joda LocalDateTime
. I need to create a java.util.Comparator
class to compare instances of MyCustomClass
by their TimeStamp
property, which is of type LocalDateTime
. I have read several postings on this (including this one), and I have tried all the methods, but none of the methods shown in the answers seem to work. For example, the following several approaches throw compilation errors:
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();
}
}
I intend to use this elsewhere in code like:
List<MyCustomClass> mccs = new ArrayList<MyCustomClass>();
// Sort by time stamp:
Collections.sort(mccs, new MyCustomClassComparator());
How do I write a Comparator
class to compare instances of MyCustomClass
based on their Joda LocalDateTime
properties?