57

I've got a collection of Duck objects and I'd like to sort them using multiple keys.

class Duck {
    DuckAge age; //implements Comparable
    DuckWeight weight; //implements Comparable
    String name;
}
List<Duck> ducks = Pond.getDucks();

eg. I want to sort them primarily by their weights, and secondarily by their age. If two ducks have the exact same weight and the exact same age, then let's differentiate them using their names as a tertiary key. I might do something like this:

Collections.sort(ducks, new Comparator<Duck>(){
    @Override
    public int compare(Duck d1, Duck d2){
        int weightCmp = d1.weight.compareTo(d2.weight);
        if (weightCmp != 0) {
            return weightCmp;
        }
        int ageCmp = d1.age.compareTo(d2.age);
        if (ageCmp != 0) {
            return ageCmp;
        }
        return d1.name.compareTo(d2.name);
    }
});

Well I do this quite frequently, but this solution doesn't smell right. It doesn't scale well, and it's easy to mess up. Surely there must be a better way of sorting Ducks using multiple keys! Does anybody know of a better solution?

EDIT removed unnecessary else branches

5
  • 6
    it doesn't look too bad, you can remove one level of indentation, by removing both else since in the if you return, so it's not needed.
    – stivlo
    Commented Nov 7, 2011 at 12:24
  • 21
    +1 for getting your ducks in order
    – Rich
    Commented Nov 7, 2011 at 15:38
  • Is there no elegant solution in core Java itself?
    – Sid
    Commented Nov 7, 2011 at 16:06
  • hey i have a question for you....i am totally unaware of how this compare thing works...does your objects "ducks" gets overwritten after being sorted?? Commented Aug 16, 2013 at 12:09
  • Collections.sort() modifies the given collection itself (instead of returning a sorted copy of the collection). So the ducks object "gets overwritten" in the sense that it is sorted in-place. (Well not actually in-place: the contents of ducks is dumped into an array, where it gets sorted, and the result is copied back into the original collection.)
    – andras
    Commented Aug 20, 2013 at 20:30

7 Answers 7

52

Guava is more elegant:

return ComparisonChain.start()
     .compare(d1.weight, d2.weight)
     .compare(d1.age, d2.age)
     .compare(d1.name, d2.name)
     .result();

Apache commons-lang has a similar construct, CompareToBuilder.

5
  • 1
    thanks, this is exactly what I wanted! Guava Ordering class looks nice as well, if you already have some Comparators and want to combine them and use them for sorting.
    – andras
    Commented Nov 7, 2011 at 12:49
  • 3
    Apache's CompareToBuilder is a tiny bit more elegant, since it also handles nulls by default, using a nulls first comparison. Guava's ComparisonChain will throw a NullPointerException unless you add a third parameter (Ordering.natural().nullsFirst()) to every .compare() call. Commented Jan 17, 2012 at 0:40
  • How can i use it to sort Arraylists?(using multiple keys)? Commented Aug 16, 2013 at 11:30
  • @JB Nizet is there any way i can use it a whole array???here only 2 objects are being sorted Commented Aug 16, 2013 at 11:46
  • You create a comparator, and use the code above inside the compare() method of the comparator. Then you sort the list using Collections.sort(comparator), just as shown in the question.
    – JB Nizet
    Commented Aug 16, 2013 at 11:46
28

Java 8 solution:

Comparator<Duck> cmp = Comparator.comparing(Duck::getWeight)
    .thenComparing(Duck::getAge)
    .thenComparing(Duck::getName);

Hooray for lambdas, method references, and default methods:)! Too bad we have to define getters, or use explicit lambdas, like so:

Comparator<Duck> cmp = Comparator
    .comparing((Duck duck)-> duck.weight)
    .thenComparing((Duck duck)-> duck.age)
    .thenComparing(duck-> duck.name);

Type inference won't work with implicit lambdas, so you have to specify the argument type of the first two lambdas. More details in this answer by Brian Goetz.

0
21
List<Duck> ducks = new ArrayList<Duck>();
Collections.sort(ducks, new Comparator<Duck>() {

  @Override
  public int compare(Duck o1, Duck o2) {

    return new org.apache.commons.lang.builder.CompareToBuilder().
        append(o1.weight, o2.weight).
        append(o1.age, o2.age).
        append(o1.name, o2.name).
        toComparison();
  }
});
6
  • How can i use it to sort Arraylists?(using multiple keys)? Commented Aug 16, 2013 at 11:45
  • Are you talking about arrays (e.g. String[]) or java.util.ArrayLists? It depends on the elements that are stored. Arrays can be sorted using the method Arrays.sort(T[], Comparator<T>) Commented Aug 16, 2013 at 13:29
  • What i meant was,that in this e.g you have just sorted 2 objects of the type duck...."public int compare(Duck o1, Duck o2)" what if i have to sort a whole arraylist of type Duck..for e.g ArrayList<Duck> dd =new ArrayList(); ????? Commented Aug 16, 2013 at 13:51
  • 1
    That's why you pass the Comparator implementation to the Collections.sort(List<Duck>, Comparator<Duck>) method which does the job of sorting the whole list. Comparator is there to compare any two elements of the list. Commented Aug 16, 2013 at 15:03
  • 1
    @IgorGanapolsky add the library to your classpath mvnrepository.com/artifact/org.apache.commons/commons-lang3 Commented Jul 17, 2014 at 6:34
14

Firstly, your solution isn't that slow.

If you really want another method, then give each duck a "score" which is essentially a single number that is the sum of their three characteristics, but with a huge weighting (excuse the almost unavoidable pun) for weight, a lesser one for age; and a very small one for the name.

You can allocate ~10 bits for each characteristic, so for each characteristic you have to be in the range 0..1023.

score = ( (weight << 10) + age) << 10 + name;

This is probably completely unneeded, but whatever :)

1
  • Nice little trick, thanks. I was going for beauty, not performance, but I'll keep this in mind:)
    – andras
    Commented Nov 7, 2011 at 12:57
6

You can use the CompareToBuilder from Apache Commons Lang. (It explains comparable, but works for Comparator too).

4

You can use chained BeanComparators from Commons BeanUtils:

Comparator comparator = new BeanComparator("weight", new BeanComparator("age"));

http://commons.apache.org/beanutils/v1.8.3/apidocs/org/apache/commons/beanutils/BeanComparator.html

0
4

I have just rewritten your code without nested else statements. Do you like it now?

@Override
public int compare(Duck d1, Duck d2){
    int weightCmp = d1.weight.compareTo(d2.weight);
    if (weightCmp != 0) {
        return weightCmp;
    }
    int ageCmp = d1.age.compareTo(d2.age);
    if (ageCmp != 0) {
        return ageCmp;
    } 

    return d1.name.compareTo(d2.age);
}
1
  • Yeah, thanks, it does look better, but the main problem was that I was chaining comparisons manually. The Guava ComparisonChain and Apache CompareToBuilder look much better.
    – andras
    Commented Nov 7, 2011 at 12:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.