Java HashMap get ()

Il metodo Java HashMap get () restituisce il valore corrispondente alla chiave specificata nella hashmap.

La sintassi del get()metodo è:

 hashmap.get(Object key)

In questo caso, hashmap è un oggetto della HashMapclasse.

get () parametri

Il get()metodo accetta un singolo parametro.

  • chiave - chiave il cui valore mappato deve essere restituito

get () Valore restituito

  • restituisce il valore a cui è associata la chiave specificata

Nota : il metodo restituisce nullse la chiave specificata è mappata a un valore nullo o la chiave non è presente nella hashmap.

Esempio 1: ottenere il valore della stringa utilizzando la chiave intera

 import java.util.HashMap; class Main ( public static void main(String() args) ( // create an HashMap HashMap numbers = new HashMap(); // insert entries to the HashMap numbers.put(1, "Java"); numbers.put(2, "Python"); numbers.put(3, "JavaScript"); System.out.println("HashMap: " + numbers); // get the value String value = numbers.get(1); System.out.println("The key 1 maps to the value: " + value); ) )

Produzione

 HashMap: (1 = Java, 2 = Python, 3 = JavaScript) La chiave 1 è mappata al valore: Java

Nell'esempio sopra, abbiamo creato una hashmap denominata numeri. Il get()metodo viene utilizzato per accedere al valore Java a cui è associata la chiave 1.

Nota : possiamo usare il metodo HashMap containsKey () per verificare se una particolare chiave è presente nella hashmap.

Esempio 2: ottenere un valore intero utilizzando la chiave stringa

 import java.util.HashMap; class Main ( public static void main(String() args) ( // create an HashMap HashMap primeNumbers = new HashMap(); // insert entries to the HashMap primeNumbers.put("Two", 2); primeNumbers.put("Three", 3); primeNumbers.put("Five", 5); System.out.println("HashMap: " + primeNumbers); // get the value int value = primeNumbers.get("Three"); System.out.println("The key Three maps to the value: " + value); ) )

Produzione

 HashMap: (Five = 5, Two = 2, Three = 3) La chiave Three corrisponde al valore: 3

Nell'esempio sopra, abbiamo utilizzato il get()metodo per ottenere il valore 3 utilizzando la chiave Tre.

Articoli interessanti...