Skip to content

Java TreeMap Get Key Using Value Example

This example shows how to get TreeMap value by key in Java. This example also shows various ways using which you can get TreeMap key using a value.

How to get key using value from TreeMap in Java?

The TreeMap class in Java is a map implementation that maps keys to values. It is very easy to get TreeMap value from the key using the get method. However, it is not so easy to do the opposite, i.e. get key by value as there is no direct method to do that. However, you can use the below given approaches if you still need to do that.

1. Using the entrySet method

Get all the entries stored in the TreeMap object using the entrySet method. Once you get all the entries, iterate through them and compare them with the desired value. If the value is found, fetch the key for that value as given below.

Output

2. Using the keySet method

Instead of getting all the entries, you can also get all the keys stored in the TreeMap using the keySet method as given below. You can also use an Iterator instead of the for loop.

Output

How about TreeMap having duplicate values mapped to different keys?

Both of the above given approaches work only if the TreeMap is having a 1:1 relationship. They do not work if the same value is mapped to different keys in the TreeMap. If the TreeMap has duplicate values, you need to change the code a little bit as given below.

Output

What is the preferred way to fetch a key using the value from the TreeMap object?

The above given approaches iterate the TreeMap in order to find the key for a matching value. This operation may not perform well if the map is too large and could slow down the execution of the code.

If you really need to have this functionality, you should consider using the data structure specifically built for this purpose called bi-maps. As the name suggests, they are bi-directional maps and supports lookups from key to value as well as value to key.

The Java standard library does not have any such map, but the Apache Commons library provides one named BidiMap. Here is how to use that.

Output

You can also use the BiMap class from the Google Guava library which supports generics too.

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

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

References:
Java 8 TreeMap

About the author

2 comments

  1. Hi!
    In test Java Object Oriented Programming Quiz 7 there is a mistake:
    Will this code compile?

    class Test{
    interface TestInterface{
    }
    }
    1. Yes
    2. No
    Incorrect answer.
    Yes is the correct choice. Defining an interface inside a class is valid in Java.
    No is shown as correct answer

Leave a Reply

Your email address will not be published.