To sort a HashSet in Java, you can use TreeSet, ArrayList instance's sort(Comparator), Collections.sort(List) or Collections.sort(List, Comparator) methods in conjunction with Comparable and Comparator to control over the sort order

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

  • With Java 8+, you can also use the ArrayList instance's sort(Comparator). The Collections.sort methods internally call to it which in turn also dispatches to the Java 8+ sort(Comparator) method of the List interface