Skip to content

Get TreeSet Element by Index in Java Example

This example shows how to get the TreeSet element by index in Java. This example also shows how to get an element from TreeSet by index using an array, list, or iterator.

How to get an element by index from Java TreeSet?

The TreeSet class in Java is a NavigableSet implementation of a TreeMap. It does not allow us to access the elements using the index. There are no direct methods to access the elements by index, but there are some workarounds using which we can do that as given below.

1. By converting to an array

The array is an index based data structure. We can convert the TreeSet object to an array and then we can access elements from it using the index as given below.


As we can see from the output, the TreeSet elements are automatically sorted in the natural order which is ascending order for the Integer type.

Note: This approach requires the allocation of a new array having the TreeSet elements. If the TreeSet has a large number of elements, it may slow down the code. Plus, we need to convert to array every time an element is added or removed from the TreeSet.

2. By converting to a List (LinkedList or ArrayList)

Instead of converting to an array, we can convert the TreeSet to ArrayList or a LinkedList object and then use the get method to get the element by index as given below.


Note: Similar to the array approach, this approach also needs to allocate a new List containing TreeSet elements. It may not perform well if the TreeSet is large. Additionally, we need to convert TreeSet to a List every time an element is added or removed from the TreeSet.

3. By iterating using an Iterator

The simplest approach is to iterate through the TreeSet elements until we reach the desired index and get the element. We can get the iterator for TreeSet elements using the iterator method.


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

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

Java 8 TreeSet

About the author

Leave a Reply

Your email address will not be published.