Java Program to Find the Index of the TreeSet Element
Last Updated :
27 Jun, 2021
Unlike the List classes like ArrayList or a LinkedList, the TreeSet class does not allow accessing elements using the index. There are no direct methods to access the TreeSet elements using the index and thus finding an index of an element is not straightforward.
Methods: There are primarily three standard methods as follows:
- By converting TreeSet to a List
- Using an Iterator
- Using the headSet() method of the TreeSet class
Method 1: By converting TreeSet to a List
The List class like ArrayList or a LinkedList provides the indexOf() method to find the element index. We can convert the TreeSet to ArrayList and then use the indexOf() method. This method returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
Syntax:
public int indexOf(Object o) ;
Parameters: This function has a single parameter, i.e, the element to be searched in the list.
Returns: This method returns the index of the first occurrence of the given element in the list and returns “-1” if the element is not in the list.
Example
Java
// Java Program to find the index of TreeSet element
// using List by converting TreeSet to a List
// Importing ArrayList, List and TreeSet classes
// from java.util package
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
// Class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating a object of the TreeSet class
// Declaring object of Integer type
TreeSet<Integer> treeSet = new TreeSet<Integer>();
// Adding the element to the TreeSet
// Custom inputs
treeSet.add(34);
treeSet.add(23);
treeSet.add(43);
treeSet.add(41);
treeSet.add(35);
treeSet.add(33);
// Printing all the elements in the TreeSet object
System.out.println("TreeSet contains: " + treeSet);
// Printing indexes of elements using indexOf()
// method Index of element number 1
System.out.println("Index of 23: "
+ indexOf(treeSet, 23));
// Index of element number 2
System.out.println("Index of 43: "
+ indexOf(treeSet, 43));
// Index of element number 3
System.out.println("Index of 35: "
+ indexOf(treeSet, 35));
// Index of element number 4
System.out.println("Index of 55: "
+ indexOf(treeSet, 55));
}
// Method - indexOf()
private static int indexOf(TreeSet<Integer> set,
Integer element)
{
// Step 1: Convert TreeSet to ArrayList or
// LinkedList
List<Integer> list = new ArrayList<Integer>(set);
// Step 2: Use the indexOf method of the List
return list.indexOf(element);
}
}
OutputTreeSet contains: [23, 33, 34, 35, 41, 43]
Index of 23: 0
Index of 43: 5
Index of 35: 3
Index of 55: -1
Method 2: Using an Iterator
Procedure:
- Iterator over TreeSet elements using the iterator method.
- Once the iterator is fetched, iterate through the elements and search for the specified element as per requirements either from the user or custom inputs as shown below for understanding purposes.
Example
Java
// Java Program to find the index of the element
// in the TreeSet using Iterator
// Using an Iterator
// Importing Iterator and TreeSet class from
// java.util package
import java.util.Iterator;
import java.util.TreeSet;
// Class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an object of TreeSet class
// Declaring object of Integer type
TreeSet<Integer> treeSet = new TreeSet<Integer>();
// Adding the elements to the TreeSet
// Custom inputs
treeSet.add(34);
treeSet.add(23);
treeSet.add(43);
treeSet.add(41);
treeSet.add(35);
treeSet.add(33);
// Printing the element in the TreeSet
System.out.println("TreeSet contains: " + treeSet);
// Printing the indexes of elements in above TreeSet
// object
System.out.println("Index of 23: "
+ indexOf(treeSet, 23));
System.out.println("Index of 43: "
+ indexOf(treeSet, 43));
System.out.println("Index of 35: "
+ indexOf(treeSet, 35));
System.out.println("Index of 55: "
+ indexOf(treeSet, 55));
}
// Method - indexOf()
private static int indexOf(TreeSet<Integer> set,
Integer element)
{
int index = -1;
// Get an iterator
Iterator<Integer> itr = set.iterator();
Integer currentElement = null;
int currentIndex = 0;
// Condition check using hasNext() method which
// holds true till single element in List is
// remaining
while (itr.hasNext()) {
currentElement = itr.next();
// Checking if the current element equals
// the element whose index is tried to search
if (currentElement.equals(element)) {
// Return the index of the element
return currentIndex;
}
// Increment the index number
currentIndex++;
}
// Return the index -1
// if the element do not exists
return index;
}
}
OutputTreeSet contains: [23, 33, 34, 35, 41, 43]
Index of 23: 0
Index of 43: 5
Index of 35: 3
Index of 55: -1
Method: 3 Using the headSet() method of the TreeSet class
The headSet() method of the TreeSet class returns a view of part of the TreeSet whose elements are less than the specified element. Since the elements of the TreeSet are automatically sorted either in the natural order of the elements or by a custom comparator, the headset size will be equal to the number of elements that are smaller or lower than the specified element. If we were to put the TreeSet elements in a List, then that number would be equal to the index of the element.
Illustration:
If the TreeSet contains [1, 2, 3, 4] then the headset of element 3 will contain elements [1, 2]. The size of the headset will be 2 and that will be the index of element 3. Thus, if we get the size of the headset, then it will be equal to the position of the element for which we have to find the index.
Example
Java
// Java Program to find the index of element
// in TreeSet using HeadSet
// Using the headSet() method of the TreeSet class
// Importing TreeSet class from
// java.util package
import java.util.TreeSet;
// Class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Making the new object of TreeSet class
TreeSet<Integer> treeSet = new TreeSet<Integer>();
// Adding the elements to the TreeSet
treeSet.add(34);
treeSet.add(23);
treeSet.add(43);
treeSet.add(41);
treeSet.add(35);
treeSet.add(33);
// Printing the elements of the TreeSet
System.out.println("TreeSet contains: " + treeSet);
// Printing the indexes of elements
// in above TreeSet object
System.out.println("Index of 23: "
+ indexOf(treeSet, 23));
System.out.println("Index of 43: "
+ indexOf(treeSet, 43));
System.out.println("Index of 35: "
+ indexOf(treeSet, 35));
System.out.println("Index of 55: "
+ indexOf(treeSet, 55));
}
// Method - indexOf() method
private static int indexOf(TreeSet<Integer> set,
Integer element)
{
int index = -1;
// If the element exists in the TreeSet
if (set.contains(element)) {
// The element index will be equal to the
// size of the headSet for the element
index = set.headSet(element).size();
}
// Return the index of the element
// Value will be -1 if the element
// do not exist in the TreeSet
return index;
}
}
OutputTreeSet contains: [23, 33, 34, 35, 41, 43]
Index of 23: 0
Index of 43: 5
Index of 35: 3
Index of 55: -1
Similar Reads
Find the position of an element in a Java TreeMap Given an element N and a TreeMap, the task is to find the position of this element in the given TreeMap in Java. Examples: Input: TreeMap = {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}, N = 20 Output: 2 Input: TreeMap = {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}, N = 5 Output: -1 Approach: T
2 min read
Java Program to Perform the Inorder Tree Traversal The binary tree is the hierarchical data structure in which each node has at most two children and it can referred to as the left child and the right child. Inorder tree traversal is one of the fundamental ways to visit all the nodes in the binary tree. It can specifically visiting the nodes in the
4 min read
Java Program to Get the First Element from LinkedHashSet LinkedHashSet is an implementation of Set Abstract Data Type (ADT). It extends from the HashSet class which in-turn implements Set Interface. The difference between the LinkedHashSet and HashSet is the property of maintaining the element ordering. LinkedList is just a container holding sequence of e
3 min read
TreeSet first() Method in Java The Java.util.TreeSet.first() method is used to return the first of the element of a TreeSet. The first element here is being referred to the lowest of the elements in the set. If the elements are of integer types then the smallest integer is returned. If the elements are of the string types then th
3 min read
Difference Between TreeSet and SortedSet in Java TreeSet is one of the implementations of the Navigable sub-interface. It is underlying data structure is a red-black tree. The elements are stored in ascending order and more methods are available in TreeSet compare to SortedSet. We can also change the sorting parameter using a Comparator. For examp
3 min read
Java Program to Construct a Binary Search Tree Binary Search Tree (BST) is the widely used data structure in computer science, primarily known for the efficient search, insertion, and deletion operations. It is the type of binary tree where each node has at most two children, referred to as the left child and the right child. Binary Search Tree
6 min read