Il Java HashMap entrySet () restituisce una vista di insieme di tutte le mappature (voci) presenti nella hashmap.
La sintassi del entrySet()
metodo è:
hashmap.entrySet()
In questo caso, hashmap è un oggetto della HashMap
classe.
parametri entrySet ()
Il entrySet()
metodo non accetta alcun parametro.
entrySet () Valore restituito
- restituisce una vista impostata di tutte le voci di una hashmap
Nota : la visualizzazione dell'insieme significa che tutte le voci dell'hashmap sono visualizzate come un insieme. Le voci non vengono convertite in un set.
Esempio 1: Java HashMap entrySet ()
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 mappings System.out.println("Set View: " + prices.entrySet()); ) )
Produzione
HashMap: (Pantaloni = 150, Borsa = 300, Scarpe = 200) Set View: (Pantaloni = 150, Borsa = 300, Scarpe = 200)
Nell'esempio sopra, abbiamo creato una hashmap denominata prezzi. Notare l'espressione,
prices.entrySet()
Qui, il entrySet()
metodo restituisce una vista impostata di tutte le voci dalla hashmap.
Il entrySet()
metodo può essere utilizzato con il ciclo for-each per iterare attraverso ogni voce della hashmap.
Esempio 2: metodo entrySet () nel ciclo for-each
import java.util.HashMap; import java.util.Map.Entry; 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 each entry of the hashmap System.out.print("Entries: "); // entrySet() returns a set view of all entries // for-each loop access each entry from the view for(Entry entry: numbers.entrySet()) ( System.out.print(entry); System.out.print(", "); ) ) )
Produzione
HashMap: (Uno = 1, Due = 2, Tre = 3) Voci: Uno = 1, Due = 2, Tre = 3,
Nell'esempio sopra, abbiamo importato il java.util.Map.Entry
pacchetto. Il Map.Entry
è la classe annidata della Map
interfaccia. Notare la linea,
Entry entry : numbers.entrySet()
Qui, il entrySet()
metodo restituisce una vista impostata di tutte le voci . La Entry
classe ci permette di memorizzare e stampare ogni voce dalla vista.
Lettura consigliata
- HashMap keySet () - restituisce la visualizzazione dell'insieme di tutte le chiavi
- Valori HashMap (): restituisce la visualizzazione dell'insieme di tutti i valori