Java Challengers #5: Sorting with Comparable and Comparator in Java

Comparable or Comparator? Choose the correct interface for the sorting algorithm you need

1 2 Page 2
Page 2 of 2

Which is the output of this code?


A)   Bart
       Homer
       Lisa
       Maggie
       Marge

B)   Maggie
       Bart
       Lisa
       Marge
       Homer

C)   Marge
       Maggie
       Lisa
       Homer
       Bart

D)   Indeterminate

TreeSet and reverse()

Looking at the code, the first thing you should notice is that we’re using a TreeSet , so the elements will be sorted automatically. The second thing is that the order of comparison is inverted, so the sorting will be done in reverse order.

When we first add elements into the list, TreeSet automatically sorts them to:


Marge
Maggie
Lisa
Homer
Bart

Then we use the reverse() method, which reverses the order of elements. So the final output would be:


Bart
Homer
Lisa
Maggie
Marge

Common mistakes with Comparable

  • Trying to sort a non-comparable object in the sort() method.
  • Using Comparable for different sorting strategies within the same object.
  • Inverting comparison in the compareTo() method so that sorting will be in reverse order, like so:
    Normal order:
    
    public int compareTo(Simpson simpson) {
    this.name.compareTo(simpson.name);
    }
    
    Inverted order:
    
    public int compareTo(Simpson simpson) {
    simpson.name.compareTo(this.name);
    }
    
  • Adding a non-comparable (any object that doesn’t implement Comparable) object in a TreeSet or TreeMap object.

What to remember about sorting with Java

  • Use Comparable when the comparison is standard for the given class.
  • Use Comparator when you need more flexibility.
  • It’s possible to use lambdas with Comparator.
  • Many Java core classes implement Comparable.
  • Use TreeMap or TreeSet when sorting a Map or a Set.
  • The compareTo() method works with both Comparable and Comparator.
  • The compareTo() method will return a positive number if one object is greater than the other, negative if it’s lower, and zero if they are the same.

Learn Java

1 2 Page 2
Page 2 of 2