Get TreeMap Key or Value using Index Java Example

This example shows how to get TreeMap key or value using the index in Java. This example also shows various ways to get TreeMap key or value by index.

How to get TreeMap key or value using an index in Java?

The TreeMap class is a Red-Black tree implementation of the Map interface and thus does not expose any methods using which we can access the TreeMap keys or values using their indices. However, if you still want you can do so using below given ways.

1. Using an array

Use the entrySet method of the TreeMap class to get a Set view of all the entries stored in the TreeMap object and then convert the entry set to an array using the toArray method. Once you get an array, you can get the entries using their index as given below.


2. Using a List

Instead of converting the entry set to an array, you can convert it to the List (ArrayList or LinkedList) object and then access the TreeMap entries using the get method of the list.


3. Using an Iterator

You can also iterate through TreeMap entries using an iterator and get the key or value located at the desired index as given below.


Important Notes:

1. All of the above given approaches iterates the TreeMap which may impact performance especially if the map is too large.

2. Converting the entry set to an array or to a List is unnecessary overhead and needs to allocate a new array or list that is costly operation in terms of performance.

3.  Any map implementation is not supposed to be accessed by index. If you need to access the key or value using the index see if you can use any of the list implementations instead of the map.

This example is a part of the TreeMap in Java Tutorial.

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

Java 8 TreeMap

About the author



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 *

Online Shopping