Skip to content
Related Articles

Related Articles

Java Program to Find the Index of the TreeSet Element
  • Last Updated : 02 Feb, 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:

  1. By converting TreeSet to a List
  2. Using an Iterator
  3. 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);
    }
}
Output
TreeSet 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: 

  1. Iterator over TreeSet elements using the iterator method.
  2.  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;
            }
  
            // Increament the index number
            currentIndex++;
        }
  
        // Return the index -1
        // if the element do not exists
        return index;
    }
}
Output



TreeSet 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;
    }
}
Output
TreeSet contains: [23, 33, 34, 35, 41, 43]
Index of 23: 0
Index of 43: 5
Index of 35: 3
Index of 55: -1

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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :