Sorting with Comparable and Comparator in Java

Comparable or Comparator—which should it be? Learn how to choose the correct interface for the sorting algorithm you need.

1 2 Page 2
Page 2 of 2

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

Video challenge! Debugging sort() and TreeSet

Debugging is one of the easiest ways to fully absorb programming concepts while also improving your code. In this video you can follow along while I debug and explain the Java sorting challenge:

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 more about Java

This story, "Sorting with Comparable and Comparator in Java " was originally published by JavaWorld.

Copyright © 2019 IDG Communications, Inc.

1 2 Page 2
Page 2 of 2