
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert HashSet to TreeSet in Java
In this article, we will learn to convert a HashSet to a TreeSet in Java. Converting from one type of collection to another is a simple process when we require them to change their behavior or the nature of our data structure.
Why Convert HashSet to TreeSet?
For the following operations, we can convert a HashSet to a TreeSet ?
-
Sorted Order: TreeSet maintains elements in ascending order.
-
Range-Based Operations: It supports operations like headSet(), tailSet(), and subSet().
- NavigableSet Features: TreeSet provides methods like higher(), lower(), ceiling(), and floor(), which are useful for navigation.
Using the TreeSet Constructor
The easiest way to do the conversion of such a HashSet is by providing the same HashSet as an argument to the TreeSet constructor.
The following are the steps to convert a HashSet to a TreeSet in Java ?
-
Create a HashSet and add some names to it.
-
Print the HashSet: The output will be unordered since HashSet does not maintain any specific order.
- Convert the HashSet to a TreeSet by passing the HashSet to the TreeSet constructor; this sorts the elements.
- Print the TreeSet: The names will now appear in their natural, sorted order (alphabetical for strings
At first, create a HashSet with string values using the add() method ?
HashSet<String> hashSet = new HashSet<String>(); hashSet.add("Bradley"); hashSet.add("Katie"); hashSet.add("Brad"); hashSet.add("Amy"); hashSet.add("Ryan"); hashSet.add("Jamie");
Now, convert the HashSet to TreeSet ?
Set<String> set = new TreeSet<String>(hashSet);
Example
Below is an example to convert a HashSet to a TreeSet in Java ?
import java.util.HashSet; import java.util.Set; import java.util.TreeSet; public class Demo { public static void main(String[] args) { HashSet<String> hashSet = new HashSet<String>(); hashSet.add("Bradley"); hashSet.add("Katie"); hashSet.add("Brad"); hashSet.add("Amy"); hashSet.add("Ryan"); hashSet.add("Jamie"); hashSet.add("Kevin"); hashSet.add("David"); System.out.println("HashSet = "+ hashSet); Set<String> set = new TreeSet<String>(hashSet); System.out.println("TreeSet = "+set); } }
Output
HashSet = [Kevin, Jamie, Ryan, Bradley, Katie, David, Brad, Amy] TreeSet = [Amy, Brad, Bradley, David, Jamie, Katie, Kevin, Ryan]
Time complexity: O(N log N), due to inserting N elements into a balanced tree.
Space complexity: O(N), as a new TreeSet is created to store the elements.