English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans cet exemple, nous allons apprendre à obtenir la clé à partir d'une valeur dans une HashMap en utilisant Java.
Pour comprendre cet exemple, vous devriez comprendre ce qui suitprogrammation Javasujet :
import java.util.HashMap; import java.util.Map.Entry; class Main { public static void main(String[] args) { //création d'une carte de hachage HashMap<String, Integer> numbers = new HashMap<>(); numbers.put("One", 1); numbers.put("Two", 2); numbers.put("Three", 3); System.out.println("HashMap: " + numbers); //la valeur à chercher pour sa clé Integer value = 3; //itération sur chaque entrée de la 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 all entries as a set.
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.