Skip to content

Java HashMap – How to Get Key from Value

Category
Programming
Covers
Java
Versions & support
About Java →
On this page

Write a Java program to get keys from the hashmap using the value.

The HashMap class is available under the java.util package. It is pretty similar to HashTable, but the HashMap is unsynchronized and also allows to stole one null key.

In this tutorial, you will learn Java examples to get keys from a HashMap based on a defined value.

Get Key for a Value in HashMap

The Entry interface provides a number of methods to access key values from a HashMap. The Entry.getValue() method returns the value based on the provided key.

Here is an example Java program to initialize a HashMap and then iterate through all key-pair using for loop.

Let’s create a file HashMapExample1.java in your system and add the below content.

Save the file and close it.

Now, compile the Java program and run. You will see the results below.

Output:
The Key for 'Peris' is 103

Get All Key Values in HashMap

Here is another example showing to get all key values from a Java HashMap.

Now, compile and run above Java program. You should see the results as below:

Output:
HashMap: {101=Delhi, 102=New York, 103=Peris, 104=Denmark}

Wrap Up

In this faq, you have learned an example to get the HashMap key based on a value in the Java programming language.

Rahul

Rahul Kumar is the founder and chief editor of TecAdmin.net. A Red Hat Certified Engineer (RHCE), he has worked in IT since 2009, with hands-on experience in Linux system administration, DevOps, web hosting, cloud platforms and automation. He started TecAdmin in 2013 to share practical, step-by-step guides, and leads its editorial work with one aim: making technical learning clear and useful for sysadmins, developers and beginners alike.

Leave a Reply

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


Back to top