Come ottenere una Key da un valore in HashMap con Java

4 apr 2022 1 min di lettura
Come ottenere una Key da un valore in HashMap con Java
Indice dei contenuti

Introduzione

Scrivi un programma Java per ottenere le chiavi dalla hashmap usando il valore.

La classe HashMap è disponibile nel pacchetto java.util. È abbastanza simile a HashTable, ma HashMap non è sincronizzato e consente anche di rubare una chiave nulla.

In questo tutorial imparerai esempi Java per ottenere chiavi da una HashMap in base a un valore definito.

Ottienere la chiave per un valore in HashMap

Crea un file HashMapExample1.java nel tuo sistema e aggiungi il contenuto seguente:

import java.util.HashMap;
import java.util.Map.Entry;
 
class HashMapExample1 {
  public static void main(String[] args) {
 
    // Define a hashmap
    HashMap<Integer, String> cities = new HashMap<>();
 
    // Adding key pair to hashmap  
    cities.put(101, "Delhi");
    cities.put(102, "New York");
    cities.put(103, "Paris");
    cities.put(104, "Denmark");
 
    // Define value to search key for 
    String value = "Paris";
 
    // Iterate through hashmap using for loop
    for(Entry<Integer, String> entry: cities.entrySet()) {
      if(entry.getValue() == value) {
        System.out.println("The Key for '" + value + "' is " + entry.getKey());
        break;
      }
    }
  }
}

Salva e chiudi il file.

Ora, compila il programma Java ed esegui. Vedrai i risultati qui sotto:

The Key for 'Paris' is 103

Ottienere tutti i valori chiave in HashMap

Ecco un altro esempio che mostra come ottenere tutti i valori chiave da una HashMap Java:

import java.util.HashMap;
 
class HashmapExample2 {
  public static void main(String[] args) {
 
    // Define a hashmap
    HashMap<Integer, String> cities = new HashMap<>();
 
    // Adding key pair to hashmap  
    cities.put(101, "Delhi");
    cities.put(102, "New York");
    cities.put(103, "Paris");
    cities.put(104, "Denmark");
 
    // Print all hashmap key pairs
    System.out.println("HashMap: " + cities);
  }
}

Ora, compila ed esegui sopra il programma Java. Dovresti vedere i risultati come di seguito:

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

Conclusione

In questo tutorial, hai imparato un esempio per ottenere la chiave HashMap in base a un valore nel linguaggio di programmazione Java.

Buy me a coffeeBuy me a coffee

Supportaci se ti piacciono i nostri contenuti. Grazie.

Successivamente, completa il checkout per l'accesso completo a Noviello.it.
Bentornato! Accesso eseguito correttamente.
Ti sei abbonato con successo a Noviello.it.
Successo! Il tuo account è completamente attivato, ora hai accesso a tutti i contenuti.
Operazione riuscita. Le tue informazioni di fatturazione sono state aggiornate.
La tua fatturazione non è stata aggiornata.