HashSet to TreeSet conversion in Java
Hello guys, today we are about to learn how to convert HashSet to TreeSet in Java. Firstly I want to give a piece of short information related to HashSet and TreeSet.
HashSet and TreeSet class is a member of Collection frameworks. A hash table that stores data value by the means of hashing. Also, it implements set type interface. Positively it stores unique elements.
The following are key points for HashSet –
- It never contains duplicate elements.
- It may allow null value too.
- It’s an unordered collection that doesn’t maintain the order in which they are feed.
- It uses a HashMap to store all its elements.
- However, it is not thread-safe.
Tree set
However TreeSet class also implements the set type interface of Collection which helps to use a tree for storage purposes. The speed to access and retrieve elements is fast. The following are important points for TreeSet.
- It always follows the ascending order.
- It is not synchronized however it can be possible if it is synchronized explicitly as shown below:
SortedSet sorted_set = Collections.synchronizedSortedSet(new TressSet(…..));
- It never allows null elements.
- It also contains a unique element too.
Algorithm
- Start
- Firstly, take input for operations as a string.
- Now, create the HashSet with the appropriate type.
- Add all the elements to HashSet by taking user input.
- Finally, create a TreeSet of HashSet elements and assign it too.
- Show the elements of TreeSet and HashSet.
- End
CODE
import java.util.*;
public class HashSet_TreeSet {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.println("Enter number of operations");
int n = in.nextInt();
HashSet<String> hashset = new HashSet<String>();
System.out.println("Enter all the elements");
for(int i=0;i<n;i++){
hashset.add(in.next());
}
System.out.println("HashSet "+hashset);
Set<String> treeset = new TreeSet<String>(hashset);
System.out.print("TreeSet : ");
for(String s : treeset)
System.out.print(s+" ");
}
}
OUTPUT
Enter number of operations 5 Enter all the elements Priya Niharika Jasmine Priyanka Aakriti HashSet [Priya, Aakriti, Jasmine, Priyanka, Niharika] TreeSet : Aakriti Jasmine Niharika Priya Priyanka
Also read: Maximum distance between two occurrences of same element in array in Java
Leave a Reply