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
Java Program to Implement TreeSet API
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 an explicit comparator is provided. This must be consistent with equals if it is to correctly
10 min read
How to Add or Append Elements to End of a TreeSet in Java?
A TreeSet is a sorted set implementation of the Set interface based on a TreeMap. It uses a Red-Black tree to store elements. Elements are sorted according to their natural ordering, or a custom Comparator provided at the time of TreeSet creation. It does not allow duplicate elements or null values.
2 min read
Java Program to Search an Element in Vector
A vector in Java is a dynamic array that can be resized as needed. It is synchronized, which means it is safe in multi-threaded programs. To find an element in a Vector we have to loop through its elements to find a match. In this article, we will learn how to search for a component in a Vector usin
3 min read
How to Iterate Over the Elements in a TreeSet in Natural Order in Java?
In Java, to iterate over the elements of a TreeSet in their Natural Order, one must either use a custom comparator provided or traverse the elements in ascending order based on their natural ordering. A TreeSet in Java keeps up with its components in arranged requests. In this article, we will learn
2 min read
How to Find the Element Index in LinkedHashSet in Java?
LinkedHashSet is used to store distinct items and get the items in which order they were inserted in Java. LinkedHashSet does not store values based on the index. But there are some methods to find the element index in LinkedHashSet in Java. Method 1: (By converting LinkedHashSet to ArrayList) To fi
4 min read
How to sort TreeSet in descending order in Java?
Given a TreeSet in Java, task is to sort elements of TreeSet in Descending Order (descreasing order).Examples: Input : Set: [2, 3, 5, 7, 10, 20] Output : Set: [20, 10, 7, 5, 3, 2] Input : Set: [computer, for, geeks, hello] Output : Set: [hello, geeks, for, computer] Approach: To make a TreeSet Eleme
1 min read
Java Program to Find Size of the Largest Independent Set(LIS) in a Given an N-array Tree
Basically, an N-array tree is such a tree structure in which each node can have a max of up to 'N' number of children. The largest independent set is a set of vertices in which no two vertexes are adjacent to each other. So basically in this program, we have to see that how can we find the size of s
4 min read
Java Program to Implement TreeMap API
The TreeMap is used to implement Map interface and NavigableMap along with the AbstractMap class in java. The map is sorted by the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. Now, in implementing TreeMap API, the task is div
6 min read
Java Program to Get Elements By Index from LinkedHashSet
LinkedHashSet is a pre-defined class in Java that is similar to HashSet. Unlike HashSet In LinkedHashSet insertion order is preserved. In order to get element by Index from LinkedHashSet in Java, we have multiple ways.Illustration:Input : 2, 3, 4, 2, 7;Processing : index = 4;Output : Element at inde
4 min read
How to Sort TreeSet Elements using Comparable Interface in Java?
TreeSet is an implementation 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 an explicit comparator is provided. To sort TreeSet elements using Comparable interface in java first, we create a cl
3 min read