1

I have my class as:

public class Element {
    int number, group, period;
    String symbol, name;
    double weight;




    public Element(int number, String symbol, String name, int group, int period, double weight) {
        this.number = number;
        this.symbol = symbol;
        this.name = name;
        this.group = group;
        this.period = period;
        this.weight = weight;
    }

I need to do a Comparator class that will first sort the Element by the group then if its in the same group sort by number. My code for that is:

class GroupComparator implements Comparator<Element> {
    @Override
    public int compare(Element a, Element b) {
        return a.group < b.group ? -1 : a.group == b.group ? a.number-b.number : 1;
    }
}

I'm not sure how to formulate it to make it work.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
George Ponta
  • 193
  • 1
  • 15

2 Answers2

1

If you're using Java 8 and above, it's as simple as the following:

Comparator.comparingInt(Element::getGroup).thenComparingInt(Element::getNumber);

This assumes that you have getter methods for both group and number named getGroup and getNumber respectively.

Jacob G.
  • 28,856
  • 5
  • 62
  • 116
1

The enhancements in Java 8's JDK make it quite easy to create such a comparator without all that boilerplate:

Comparator<Element> groupComparator =
    Comparator.comparingInt(e -> e.group).thenComparingInt(e -> e.number);
Mureinik
  • 297,002
  • 52
  • 306
  • 350