TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided.
We have the element in the TreeSet and we want to print the Element from the TreeSet using the index.
TreeSet<Integer> set = new TreeSet(); set.add(2); set.add(3); set.add(9); set.add(5); // TreeSet always used to get prevent // from the duplicates in the increasing order Set Contains -> [2,3,5,9]
So, we have the Element in set -> [2, 3, 5, 9] .Now we cannot access the Element Directly So to access the Element we need to convert the set to array or list to access the element.
So there are many ways to get the element by index:
- Converting TreeSet to array by traversing through the whole TreeSet and adding the element to array one by one.
- Converting TreeSet to array using .toArray() method.
- Converting TreeSet to ArrayList.
Method 1: Simply converting the TreeSet to array
- We simply create an empty array.
- We traverse the given set and one by one add elements to the array
2 3 5 9 5
Method 2: Using .toArray() Method
- First converting the set to array using .toArray() method.
- And accessing the Element from the Array by index.
2 3 5 9 5
Method 3: Converting to ArrayList
- First Converting the set to list by directly using the constructor.
- And then getting the Element from the List through index
2 3 5 9 5
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.