First, HashSet
does NOT maintain any order:
It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time
The implementation of a SortedSet
is TreeSet
which may use a natural order for objects implementing Comparable
interface (thus implementing compareTo
method), or a custom comparator via constructor public TreeSet(Comparator<? super E> comparator)
So, class WeeklyDataProper
may implement Comparable
interface as follows (null checks omitted here):
public class WeeklyDataProper extends WeeklyData implements Comparable<WeeklyDataProper> {
// getters getCountry / getWeek implemented in the parent
// ...
@Override
public void int compareTo(WeeklyDataProper that) {
int result = this.getCountry().compareTo(that.getCountry());
if (result == 0) {
result = Integer.compare(this.getWeek(), that.getWeek());
}
return result;
}
}
However, it may be a bit redundant to implement a separate subclass just to sort the set of WeeklyData
, therefore the sorted set of WeeklyData
may be retrieved with the custom comparator:
SortedSet<WeeklyData> sorted = new TreeSet<>(
Comparator.<WeeklyData>comparing(WeeklyData::getCountry)
.thenComparingInt(WeeklyData::getWeek)
);