2

I have a class with the following variables (entities):

Identifier  
Entry_Number  
Rest_of_the_data

I'd like to sort the instances of this class as follows:
Sort the instances by the Identifier variable, then for instances with the same Identifier values, sort them by the Entry_Number variable.

I know I can implement Comparable with one of these entities as the key, but I don't know how to go about this to sort sequentially on two entities.
That is, after sorting by the Identifier when I sort by the Entry_Number, the initial sorting should not be disturbed - the second sorting should apply only to those instances with the same Identifier values.

So, in effect, I want to be able to pass as "second key" item to resolve ties.

Hashbrown
  • 12,091
  • 8
  • 72
  • 95
sanjeev mk
  • 4,276
  • 6
  • 44
  • 69

2 Answers2

6

You can compare by two fields almost as easily as you can by one. Create a Comparator<YourClass> instance with the following compare() method:

public int compare(YourClass a, YourClass b) {
    int idDiff = a.getIdentifier().compareTo(b.getIdentifier());
    if (idDiff != 0) {
        return idDiff;
    }
    return a.getEntryNumber().compareTo(b.getEntryNumber());
}

If you have null values, or primitives, you will have to adjust.

rolfl
  • 17,539
  • 7
  • 42
  • 76
0

You can also make use of Guava ComparisonChain:

public int compare(X a, X b) {
    return ComparisonChain.start()
     .compare(a.id, b.id)
     .compare(a.dateField, b.dateField)
     .result();
}

Note that this is lazy comparison, it means that comparisions are performed until first non-zero (meaning not-equal) result is found.

Maciej Dobrowolski
  • 11,561
  • 5
  • 45
  • 67