0

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
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
nme
  • 19
  • 3
  • How to write a two-criteria compareTo: https://stackoverflow.com/a/30041805/14215102 –  Jan 25 '22 at 08:53
  • Does this answer your question? [Java comparator: Two ordering criteria](https://stackoverflow.com/questions/16959072/java-comparator-two-ordering-criteria) – Pirate Jan 25 '22 at 08:58
  • @Pirate: The natural order of a class is defined by implementing [java.lang.Comparable](https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html) and not by using java.util.Comparator. Although the logic is similar since the question requires implementing a natural order in the class the linked question doesn't really fit 100%. – OH GOD SPIDERS Jan 25 '22 at 09:36

1 Answers1

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)
);
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42