Java HashMap keySet ()

Il metodo Java HashMap keySet () restituisce una vista dell'insieme di tutte le chiavi presenti nelle voci dell'hashmap.

La sintassi del keySet()metodo è:

 hashmap.keySet()

In questo caso, hashmap è un oggetto della HashMapclasse.

Parametri keySet ()

Il keySet()metodo non accetta alcun parametro.

keySet () Valore restituito

  • restituisce una vista impostata di tutte le chiavi della hashmap

Nota : la vista set mostra solo tutte le chiavi dell'hashmap come un set. La vista non contiene chiavi effettive. Per ulteriori informazioni sulla visualizzazione in Java, visitare la visualizzazione di una raccolta.

Esempio 1: Java HashMap keySet ()

 import java.util.HashMap; class Main ( public static void main(String() args) ( // create an HashMap HashMap prices = new HashMap(); // insert entries to the HashMap prices.put("Shoes", 200); prices.put("Bag", 300); prices.put("Pant", 150); System.out.println("HashMap: " + prices); // return set view of all keys System.out.println("Keys: " + prices.keySet()); ) )

Produzione

 HashMap: (Pantaloni = 150, Borsa = 300, Scarpe = 200) Chiavi: (Pantaloni, Borsa, Scarpe)

Nell'esempio sopra, abbiamo creato una hashmap denominata prezzi. Notare l'espressione,

 prices.keySet()

Qui, il keySet()metodo restituisce una vista impostata di tutte le chiavi presenti nella hashmap.

Il keySet()metodo può anche essere usato con il ciclo for-each per iterare attraverso ogni chiave della hashmap.

Esempio 2: metodo keySet () nel ciclo for-each

 import java.util.HashMap; class Main ( public static void main(String() args) ( // Creating a HashMap HashMap numbers = new HashMap(); numbers.put("One", 1); numbers.put("Two", 2); numbers.put("Three", 3); System.out.println("HashMap: " + numbers); // access all keys of the HashMap System.out.print("Keys: "); // keySet() returns a set view of all keys // for-each loop access each key from the view for(String key: numbers.keySet()) ( // print each key System.out.print(key + ", "); ) ) )

Produzione

 HashMap: (Uno = 1, Due = 2, Tre = 3) Tasti: Uno, Due, Tre,

Nell'esempio sopra, abbiamo creato una hashmap denominata numeri. Notare la linea,

 String key: numbers.keySet()

In questo caso, il keySet()metodo restituisce una vista impostata di tutte le chiavi . La chiave variabile accede a ciascuna chiave dalla vista.

Nota : la chiave di HashMapè di Stringtipo. Quindi, abbiamo utilizzato la Stringvariabile per accedere alle chiavi.

Lettura consigliata

  • HashMap entrySet () - restituisce la vista dell'insieme di tutte le mappature (voci)
  • Valori HashMap (): restituisce la visualizzazione dell'insieme di tutti i valori

Articoli interessanti...