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:
Inverted order:public int compareTo(Simpson simpson) { this.name.compareTo(simpson.name); }
public int compareTo(Simpson simpson) { simpson.name.compareTo(this.name); }
- Adding a non-comparable (any object that doesn’t implement
Comparable
) object in aTreeSet
orTreeMap
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
orTreeSet
when sorting aMap
or aSet
. - The
compareTo()
method works with bothComparable
andComparator
. - 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
- Check out Timo Bingmann's Visualization and 'audibilization' of 15 sorting algorithms in 6 minutes.
- Go deeper with anonymous inner classes, lambda expressions, and other functional programming techniques in Java.
- Get quick code tips like ths one: Read all of Rafael's articles in the InfoWorld Java Challengers series.
- Check out all the videos in Rafael's Java Challengers video playlist.
- Find even more Java Challengers on Rafael's Java Challengers blog and in his book, with more than 70 code challenges.
This story, "Sorting with Comparable and Comparator in Java " was originally published by JavaWorld.