'The default (natural) sorting order is: Country and then Week

Implement the class: WeeklyDataProper that extends the class WeeklyData.

Requirements:

  • The default (natural) sorting order is: Country and then Week
  • The class could be properly used in a HashSet collection. Two objects are considered equal if they have the same Country and Week attributes.

How can I do the first part of the question? by compareTo method?

Right now the result is:

int week, String country

I need :

String country, int week


Solution 1:[1]

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)
);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nowhere Man