HashSet in Java is an unordered and no-duplicate elements collection. To sort it, you can try using TreeSet or ArrayList with Collections

Let's define two object classes (one implements Comparable interface and one doesn't) and implement some unit test classes to see the examples in practice



The above compareTo method provides the default / natural order in ascending to ComparableBook objects. If you want the default order in descending, try below

@Override
public int compareTo(ComparableBook o) {  
    return o.title.compareTo(this.title);
}

Using TreeSet, O(nlogn) time

  • Sort the HashSet by creating a new TreeSet with the constructor TreeSet(Collection) to copy all elements from the specified collection you want to sort

  • All elements inserted into the TreeSet must implement the Comparable interface

    They also must be mutually comparable: : e1.compareTo(e2) must not throw a ClassCastException for any elements in the set


Using ArrayList, O(nlogn) time

  • Sort the HashSet by creating a new ArrayList with the constructor ArrayList(Collection) to copy all elements from the specified collection you want to sort

  • Using Collections.sort(List) to sort Comparable implemented objects

  • Using Collections.sort(List, Comparator) to control over the sort order or to provide natural ordering to non-Comparable implemented objects