Wouldn't it be easier to just retrieve the list of Periods in a microflow, using ValidFrom as the primary sort attribute, and ValidTo as the secondary?
Anyway, in Java you'd do something like this:
public int compare(Period period1, Period period2) {
int validFromCompare = period1.getValidFrom().compareTo(period2.getValidFrom());
return validFromCompare == 0 ? period1.getValidTo().compareTo(period2.getValidTo()) : validFromCompare;
}
Note that this requires ValidFrom and ValidTo to be set, i.e. the value empty might cause problems.