Convert HashSet to TreeSet in Java
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.TreeSet; class Main { public static void main(String[] args) { Set<String> hashSet = new HashSet<>(Arrays.asList("RED", "BLUE", "GREEN")); Set<String> treeSet = new TreeSet<>(hashSet); System.out.println(treeSet); // [BLUE, GREEN, RED] } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.TreeSet; class Main { public static void main(String[] args) { Set<String> hashSet = new HashSet<>(Arrays.asList("RED", "BLUE", "GREEN")); Set<String> treeSet = new TreeSet<>(Arrays.asList("YELLOW")); treeSet.addAll(hashSet); System.out.println(treeSet); // [BLUE, GREEN, RED, YELLOW] } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import com.google.common.collect.Sets; import java.util.Arrays; import java.util.HashSet; import java.util.Set; class Main { public static void main(String[] args) { Set<String> hashSet = new HashSet<>(Arrays.asList("RED", "BLUE", "GREEN")); Set<String> treeSet = Sets.newTreeSet(hashSet); System.out.println(treeSet); // [BLUE, GREEN, RED] } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.util.*; import java.util.stream.Collectors; class Main { public static void main(String[] args) { Set<String> hashSet = new HashSet<>(Arrays.asList("RED", "BLUE", "GREEN")); Set<String> treeSet = hashSet.stream() .collect(Collectors.toCollection(TreeSet::new)); System.out.println(treeSet); // [BLUE, GREEN, RED] } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.util.*; import java.util.stream.Collectors; class Main { // Construct a new `TreeSet<String>` from `HashSet<Integer>` public static Set<String> getInstance(Set<Integer> hashSet) { return hashSet.stream() .map(String::valueOf) .collect(Collectors.toCollection(TreeSet::new)); } public static void main(String[] args) { Set<Integer> hashSet = new HashSet<>(Arrays.asList(1, 2, 3)); Set<String> treeSet = getInstance(hashSet); System.out.println(treeSet); // ["1", "2", "3"] } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.TreeSet; class Main { // Construct a new `TreeSet<String>` from `HashSet<Integer>` public static Set<String> getInstance(Set<Integer> hashSet) { Set<String> treeSet = new TreeSet<>(); for (Integer i: hashSet) { treeSet.add(String.valueOf(i)); } return treeSet; } public static void main(String[] args) { Set<Integer> hashSet = new HashSet<>(Arrays.asList(1, 2, 3)); Set<String> treeSet = getInstance(hashSet); System.out.println(treeSet); // ["1", "2", "3"] } } |
That’s all about converting a HashSet to a TreeSet in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)