TreeSet

TreeSet is similar to HashSet in that it prevents duplicates. But it also keeps the list sorted. It works just like the sort() method in that if you make a TreeSet without giving it a Comparator, the TreeSet uses each object’s compareTo() method for the sort. But you have the option of passing a Comparator to the TreeSet constructor, to have the TreeSet use that instead.

The downside to TreeSet is that if you don’t need sorting, you’re still paying for it with a small performance hit. But it is very minor.

Sorting via custom field, not using Object’s compareTo() method

If we want the TreeSet to sort on something different (i.e., to NOT use SongV4’s compareTo() method), we need to pass in a Comparator (or a lambda) to the TreeSet constructor. Then we’d use songSet.addAll() to add the songList values into the TreeSet.

Set<Song> songSet = new TreeSet<>((o1,o2)-> o1.getBpm()-o2.getBpm());
songSet.addAll(songList);

TreeSet elements MUST be comparable

You have to tell the TreeSet how to sort objects.

One of this must be true:

The elements in the list must be of a type that implements Comparable

The Book class on the previous page didn’t implement Comparable, so it wouldn’t work at runtime. Think about it, the poor TreeSet’s sole purpose in life is to keep your elements sorted, and once again—it had no idea how to sort Book objects! It doesn’t fail at compile-time, because the TreeSet add() method doesn’t take a Comparable type. The TreeSet add() method takes whatever type you used when you created the TreeSet. In other words, if you say new TreeSet(), the add() method is essentially add(Book). And there’s no requirement that the Book class implement Comparable! But it fails at runtime when you add the second element to the set. That’s the first time the set tries to call one of the object’s compareTo() methods and...can’t.

You use the TreeSet’s overloaded constructor that takes a Comparator

TreeSet works a lot like the sort() method—you have a choice of using the element’s compareTo() method, assuming the element type implemented the Comparable interface, OR you can use a custom Comparator that knows how to sort the elements in the set. To use a custom Comparator, you call the TreeSet constructor that takes a Comparator.