This post will discuss how to convert a HashSet to a TreeSet in Java. The resultant TreeSet should contain all elements of the HashSet, sorted by their natural ordering.

A HashSet is much faster than TreeSet (O(1) time versus O(log(n)) time for most operations like add, remove and contains) but offers no ordering guarantees like TreeSet. In a TreeMap, the elements are ordered using their natural ordering, or by specified Comparator. Here are some of the ways to convert a HashSet to a TreeSet in Java:

1. Using TreeSet() constructor

The simplest and most straightforward way to convert a HashSet to a TreeSet is using the parameterized constructor of TreeSet that accepts a Collection as an argument. We just need to create a new TreeSet object and pass the HashSet object as a parameter to it. For example:

Download  Run Code

2. Using TreeSet.addAll() method

To add elements of a HashSet to an existing TreeSet object, we can pass the HashSet object to the addAll() method of TreeSet instance. This method adds all elements of the specified collection to the TreeSet. This is similar to the previous method, but instead of passing the HashSet object to the constructor, we pass it to the addAll() method of a TreeSet object. For example:

Download  Run Code

3. Using Guava Library

Another option is using third-party library such as Guava, which provides utility methods for creating and manipulating Collections. Guava provides the Sets.newTreeSet() method that takes an Iterable as an argument and returns a new TreeSet containing the same elements as the iterable. For example:

Download Code

4. Using Stream API

The Stream API allows us to convert a collection into a stream and then collect the elements of the stream into another collection using a collector. So, we can convert HashSet to a Stream and collect elements of a stream into a TreeMap using the Stream.collect() method, which accepts a collector. We can use collector returned by Collectors.toCollection() method that takes a supplier of the desired collection as an argument. We can pass a reference to the TreeSet constructor (TreeSet::new) as a Supplier. For example:

Download  Run Code

 
If HashSet and TreeSet is expected to have different types, we’ll need to convert them manually. The Stream API also allows us to perform conversion between incompatible types. For example:

Download  Run Code

5. Using a loop

This post is incomplete without re-inventing the wheels. A naive and manual solution is to create an empty TreeSet instance and then use a for-each loop to traverse the HashSet and add each element to the TreeSet. This can also perform type conversion between incompatible types. For example:

Download  Run Code

That’s all about converting a HashSet to a TreeSet in Java.