0

Given a the following class:

class Boo {
    private final String propertyX;
    private final Double propertyY;
    private final Integer propertyZ;
}

How would one go about constructing a Comparator which would result in instances of the class being ordered by propertyX then by propertyY then by propertyZ when Collection.sort(...) is called on a Collection<Boo>.

Is a Comparator the way to go?

auser
  • 6,307
  • 13
  • 41
  • 63
  • 1
    possible duplicate of [Best way to compare objects by multiple fields?](http://stackoverflow.com/questions/369512/best-way-to-compare-objects-by-multiple-fields) – NPE Jun 07 '12 at 15:35
  • I don't know why @sudocode deleted his answer. It pointed to [this excellent post](http://stackoverflow.com/questions/1421322/how-do-i-sort-a-list-with-multiple-sort-parameters/1421458#1421458) which answers your question. – missingfaktor Jun 07 '12 at 15:53
  • Answer by @Yishai in this post demonstrates elegant use of enum for custom sorting and grouped sorting (multiple arguments) utilizing comparator chaining. – gunalmel Sep 16 '12 at 04:25

2 Answers2

4

You literally do what you suggest.

Comparator<Boo> booCmp = new Comparator<Boo>() {
    @Override
    public int compare(Boo o1, Boo o2) {
        int cmp = o1.propertyX.compareTo(o2.propertyX);
        if (cmp == 0)
            cmp = o1.propertyY.compareTo(o2.propertyY);
        if (cmp == 0)
            cmp = o1.propertyZ.compareTo(o2.propertyZ);
        return cmp;
    }
};
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Does this solution not break the rules for the Comparator.compare method? http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Comparator.html – auser Jun 07 '12 at 15:44
  • The only thing I can think of is if you don't implement `equals` similarly. Do you have something in mind? – Peter Lawrey Jun 07 '12 at 16:01
0

@sudocode gave a good answer but I think it is even too much for you. Just implement your custom comparator that compares propertyX, then propertyY. Use this comparator with Collections.sort() or Arrays.sort()

AlexR
  • 114,158
  • 16
  • 130
  • 208