English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Java

contrôle de flux Java

Java tableau

Java orienté objet (I)

Java orienté objet (II)

Java orienté objet (III)

Gestion des exceptions Java

Java Liste (List)

Java Queue (file d'attente)

Java Map

Java Set

Java entrées-sorties (I/O)

Lecteur Java/Écrivain

autres sujets Java

Programme Java pour obtenir la clé à partir d'une HashMap

Java instance大全

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 :

exemple : obtenir la clé d'une valeur donnée dans une HashMap

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.

Java instance大全