Convert HashSet to TreeSet in Java

In this post, we will see how to convert HashSet to TreeSet in Java. The resultant TreeSet should contain all elements of the HashSet, sorted by their natural ordering.


 

We know that 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.

 
Below are few ways to convert HashSet to TreeSet in Java –

 

1. Java 8

The idea is to convert HashSet to a Stream and collect elements of a stream in a TreeMap using Stream.collect() method which accepts a collector.

We can use collector returned by Collectors.toCollection() method that can accept desired constructor reference TreeSet::new.

 

Download   Run Code

Output:

[BLUE, GREEN, RED]

 

2. Plain Java

To construct a new TreeSet from HashSet, we can either pass HashSet object to TreeSet constructor or to addAll() method.

 

3. Google’s Guava library

Guava also provides TreeSet implementation which can be used to create an empty TreeSet instance.

 

4. Naive Solution

This post is incomplete without re-inventing the wheels. Naive solution would be to create an empty TreeSet instance and add all elements present in the HashSet to it one by one.

 

5. Conversion between incompatible types

 
If HashSet and TreeSet is expected to have incompatible types, we’ll need to convert them manually:

We can do better in Java 8 as illustrated below:

or even better,

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz