Skip to content

Java HashMap Get First Key Value without Iterating Example

This example shows how to get first key value from the Java HashMap without iterating over it using various approaches including using the Iterator, keySet method, values method, and Java 8 stream.

How to get first key from Java HashMap?

The HashMap class in Java does not guarantee the order of the mappings. It means that you may not get the key-value pairs in the same order in which they were inserted into the map. In other words, you may get different key-value pairs for the different run.

If you want to get the first key-value pair that was interested first in the map, you need to use a collection that offers the guaranteed order of the entries like TreeMap or LinkedHashMap instead of the HashMap class.

Let’s have a look at the below given example.

Output

As you can see from the output, the order of the second and third entries are not the same as their insertion orders.

So instead of the first key or first value, I will show you how to get one key or one value from the HashMap.

How to get one key or value from HashMap using the Iterator?

You can use the Iterator to get one key from the map object as given below without iterating the HashMap object.

Output

Similarly, you can get one value from the HashMap using the below given code.

Output

The above example gets the one value from the HashMap object using the key returned by the first call of the next method of an iterator of the key set. You can directly obtain an iterator for all the values of the HashMap as given below.

Output

Note that we have not iterated the map object to get one key or value, we just obtained the iterator object and called the next method once.

How to get one key or value from HashMap using the toArray method (Not recommended)?

You can use the toArray method of the Set and Collections returned by the keySet and values method respectively of the HashMap class. You can then get the first element of an array to get one key or value using the index as 0.

Output

Similarly, you can get one value from the HashMap using the values method instead of the keySet method as given below.

Output

This approach is not recommended as it unnecessarily creates a new array and thus may have a negative impact on the performance of the code.

How to get one key or value using the Java 8 stream?

If you are using Java version 8 or above, you can use the stream to get one key or value from the HashMap as given below.

Output

Important Note: It is not guaranteed to get the key or value which was inserted first into the HashMap object. You may get different key or value if you modify the map object using any of the approaches given above.

This example is a part of the HashMap in Java tutorial.

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

About the author

Leave a Reply

Your email address will not be published.