Find Index of TreeSet Element in Java

This example shows how to find an index of the specified element in Java TreeSet. The example also shows how to find the element index using the headSet method, iterator, and List.

How to find the element index in Java TreeSet?

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 straight forward. However, we can find the index using below given approaches.

1. 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.

For example, 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.

The below given example shows how to implement the TreeSet indexOf method using this approach.

Output

2. By converting it 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 as given below.

Output

Note: This approach unnecessarily creates a new List from the TreeSet to find an element index. If the TreeSet has a very large number of elements, this can slow down the performance of the code.

3. Using an Iterator

We can get the Iterator over TreeSet elements using the iterator method. Once we get an iterator, we can iterate through the elements and search for the specified element as given below.

Output

This example is a part of the TreeSet in Java Tutorial with Examples.

Please let me know your views in the comments section below.

References:
Java 8 TreeSet

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *