Java Program to Get the TreeSet Element By Index
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
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main (String[] args) {
TreeSet<Integer> s = new TreeSet<Integer>();
s.add( 2 );
s.add( 3 );
s.add( 9 );
s.add( 5 );
int n = s.size();
int arr[] = new int [n];
int i = 0 ;
for ( int ele : s)
arr[i++] = ele;
for ( int res : arr)
{
System.out.print(res+ " " );
}
System.out.println();
System.out.print(arr[ 2 ]);
}
}
|
Method 2: Using .toArray() Method
- First converting the set to array using .toArray() method.
- And accessing the Element from the Array by index.
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main (String[] args) {
TreeSet<Integer> s = new TreeSet<Integer>();
s.add( 2 );
s.add( 3 );
s.add( 9 );
s.add( 5 );
int n = s.size();
Integer arr[] = new Integer[n];
arr = s.toArray(arr);
for ( int ele : arr)
{
System.out.print(ele+ " " );
}
System.out.println();
System.out.print(arr[ 2 ]);
}
}
|
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
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main (String[] args) {
TreeSet<Integer> s = new TreeSet<Integer>();
s.add( 2 );
s.add( 3 );
s.add( 9 );
s.add( 5 );
int n = s.size();
List<Integer> list= new ArrayList<Integer>(s);
for ( int ele : list){
System.out.print(ele+ " " );
}
System.out.println();
System.out.print(list.get( 2 ));
}
}
|
Last Updated :
28 Dec, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...