English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this example, we will learn how to get the key from a HashMap using values in Java.
To understand this example, you should know the followingJava ProgrammingTopic:
import java.util.HashMap; import java.util.Map.Entry; class Main { public static void main(String[] args) { //Create a hash map HashMap<String, Integer> numbers = new HashMap<>(); numbers.put("One", 1); numbers.put("Two", 2); numbers.put("Three", 3); System.out.println("HashMap: " + numbers); //the value to search for its key Integer value = 3; //Iterate over each entry in the hashmap for(Entry<String, Integer> entry: numbers.entrySet()) { //If the given value is equal to the value from the entry //Print the corresponding key if(entry.getValue() == value) { System.out.println(value + "The key of the value is:" + entry.getKey()); break; } } } }
Output Result
HashMap: {One=1, Two=2, Three=3} 3 The key of the value is: Three
In the above example, we created a hash map named numbers. Here, we want to get the value 3 The key. Note this line,
Entry<String, Integer> entry : numbers.entrySet()
Here, the entrySet() method returns a view of the set of all entries.
entry.getValue() - Get the value from the entry
entry.getKey() - Get the key from the entry
Inside the if statement, we check if the value in the entry is the same as the given value. If the value matches, we will get the corresponding key.