CodeGym /Java Blog /Random-IT /Come utilizzare il metodo keySet in java.util.Map
John Squirrels
Livello 41
San Francisco

Come utilizzare il metodo keySet in java.util.Map

Pubblicato nel gruppo Random-IT
Se hai bisogno di ottenere tutte le chiavi contenute nella tua mappa , puoi utilizzare il metodo java.util.HashMap.keySet() davvero utile. In questo articolo spiegheremo come funziona. Come sai, la classe HashMap implementa l' interfaccia Map , quindi negli esempi useremo il metodo HashMap keySet() .

Firma del metodo HashMap keySet() e principio di funzionamento

Il metodo Set<K> keySet() restituisce una vista Set delle chiavi contenute in questa mappa. La caratteristica di questa collezione Set, che conserva le chiavi, è che non possono esserci elementi duplicati in essa. Il set è supportato dalla mappa. Ciò significa che se qualcosa è stato modificato nella mappa, si riflette nel set e viceversa. Ad esempio, puoi rimuovere elementi da questo set e le chiavi e i valori corrispondenti vengono automaticamente rimossi dalla mappa, ma non puoi aggiungere nuovi elementi al suo interno.

Esempi di HashMap keySet()

Creiamo una HashMap con i nomi dei nostri amici e le loro chiavi digitali e poi stampiamo il Set delle chiavi usando il metodo HashMap keySet() .

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class KeySetDemo {
   public static void main(String[] args) {
       Map<Integer, String> myHashMap = new HashMap<>();
       myHashMap.put(1, "John");
       myHashMap.put(2, "Ivy");
       myHashMap.put(3, "Ricky");
       myHashMap.put(4, "Andrew");
       myHashMap.put(5, "Alex");

       //using map.keyset() method and print out the result
       Set<Integer> myKeySet = myHashMap.keySet();
       System.out.println("myKeySet of the map: "+myKeySet);
L'uscita è:
chiavi della mappa: [1, 2, 3, 4, 5]
Oltre al metodo java.util.HashMap.keySet() in Java esiste un metodo entrySet() , restituisce anche un Set , ma questo set contiene coppie chiave-valore. Ecco un esempio con entrambi i metodi java.util.HashMap.keySet() e java.util.HashMap.entrySet() :

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class KeySetDemo {
   public static void main(String[] args) {
       Map<Integer, String> myHashMap = new HashMap<>();
       myHashMap.put(1, "John");
       myHashMap.put(2, "Ivy");
       myHashMap.put(3, "Ricky");
       myHashMap.put(4, "Andrew");
       myHashMap.put(5, "Alex");

       //using map.keyset() method and print out the result
       Set<Integer> myKeySet = myHashMap.keySet();
       System.out.println("keys of the map: " + myKeySet);
       System.out.println("keys and values of the map: " );
       for( Map.Entry e : myHashMap.entrySet()){
           System.out.println(e.getKey() + " : " + e.getValue());
       }
   }
}
Ecco l'output:
chiavi della mappa: [1, 2, 3, 4, 5] chiavi e valori della mappa: 1 : John 2 : Ivy 3 : Ricky 4 : Andrew 5 : Alex
Ora proviamo a rimuovere un elemento dal keySet e assicurarci che influisca sulla nostra HashMap originale .

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class KeySetDemo {
   public static void main(String[] args) {
       Map<Integer, String> myHashMap = new HashMap<>();
       myHashMap.put(1, "John");
       myHashMap.put(2, "Ivy");
       myHashMap.put(3, "Ricky");
       myHashMap.put(4, "Andrew");
       myHashMap.put(5, "Alex");

       //using map.keyset() method and print out the result
       Set<Integer> myKeySet = myHashMap.keySet();
       System.out.println("keys of the map: " + myKeySet);
      myKeySet.remove(4);
       System.out.println("myHashMap after removing an element from myKeySet: " + myHashMap);
       System.out.println("keys of the map: " + myKeySet);
   }
}
L'uscita è:
chiavi della mappa: [1, 2, 3, 4, 5] myHashMap dopo aver rimosso un elemento da myKeySet: {1=John, 2=Ivy, 3=Ricky, 5=Alex} chiavi della mappa: [1, 2 , 3, 5]
Come puoi vedere, abbiamo rimosso una chiave "4" dal Set , e ciò ha comportato la rimozione di una coppia "4-Alex" dalla nostra HashMap . Ora proviamo ad aggiungere una chiave a keySet() :

import java.util.HashMap;
       import java.util.Map;
       import java.util.Set;

public class KeySetDemo {
   public static void main(String[] args) {
       Map<Integer, String> myHashMap = new HashMap<>();
       myHashMap.put(1, "John");
       myHashMap.put(2, "Ivy");
       myHashMap.put(3, "Ricky");
       myHashMap.put(4, "Andrew");
       myHashMap.put(5, "Alex");

       //using map.keyset() method and print out the result
       Set<Integer> myKeySet = myHashMap.keySet();
       System.out.println("keys of the map: " + myKeySet);
       myKeySet.add(7);

   }
}
In questo caso otterremo un'eccezione, perché il nostro keySet è connesso alla nostra hashMap :
chiavi della mappa: [1, 2, 3, 4, 5] Eccezione nel thread "main" java.lang.UnsupportedOperationException in java.base/java.util.AbstractCollection.add(AbstractCollection.java:251) in KeySetDemo.main (KeySetDemo.java:20) Processo terminato con codice di uscita 1
Commenti
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION