Ottieni le chiavi da HashMap in Java


167

Ho un Hashmap in Java come questo:

private Map<String, Integer> team1 = new HashMap<String, Integer>();

Quindi lo riempio così:

team1.put("United", 5);

Come posso ottenere le chiavi? Qualcosa del tipo: team1.getKey()restituire "Uniti".


Cosa ti aspetti team1.getKey()di restituire se: (1) la mappa è vuota o (2) se contiene più chiavi?
— NPE,

intdovrebbe essere usato per singoli come questo.
— Stommestack

Risposte:


313

A HashMapcontiene più di una chiave. È possibile utilizzare keySet()per ottenere il set di tutte le chiavi.

team1.put("foo", 1);
team1.put("bar", 2);

memorizzerà 1con chiave "foo"e 2con chiave "bar". Per scorrere su tutte le chiavi:

for ( String key : team1.keySet() ) {
    System.out.println( key );
}

stamperà "foo"e "bar".


Ma in questo caso ho solo una chiave per ogni valore. Non è possibile scrivere qualcosa come team1.getKey ()?
— masb

No, hai una mappa con un elemento. Ma è una mappa: una struttura che può contenere più di un elemento.
— Matteo,

13
Qual è il punto di una mappa con una sola chiave? Crea una classe con un campo chiave e un campo valore.
— JB Nizet,

Ho frainteso il mio problema. Grazie per le tue risposte
— masb

3
Se si desidera memorizzare tutte le chiavi nell'elenco di array:List<String> keys = new ArrayList<>(mLoginMap.keySet());
— Pratik Butani,

50

Questo è fattibile, almeno in teoria, se conosci l'indice:

System.out.println(team1.keySet().toArray()[0]);

keySet() restituisce un set, quindi lo converti in un array.

Il problema, ovviamente, è che un set non promette di mantenere il tuo ordine. Se hai solo un oggetto nella tua HashMap, sei bravo, ma se ne hai di più, è meglio passare in rassegna la mappa, come hanno fatto altre risposte.


Questo è utile in uno scenario di test di unità in cui hai il pieno controllo sul contenuto del tuo HashMap. Bello spettacolo.
— risingTide

Niente di sapere l'indice nella domanda.
— Marchese di Lorne,

23

Controllare questo.

https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html

(Utilizzare java.util.Objects.equalsperché HashMap può contenere null)

Utilizzando JDK8 +

/**
 * Find any key matching a value.
 *
 * @param value The value to be matched. Can be null.
 * @return Any key matching the value in the team.
 */
private Optional<String> getKey(Integer value){
    return team1
        .entrySet()
        .stream()
        .filter(e -> Objects.equals(e.getValue(), value))
        .map(Map.Entry::getKey)
        .findAny();
}

/**
 * Find all keys matching a value.
 *
 * @param value The value to be matched. Can be null.
 * @return all keys matching the value in the team.
 */
private List<String> getKeys(Integer value){
    return team1
        .entrySet()
        .stream()
        .filter(e -> Objects.equals(e.getValue(), value))
        .map(Map.Entry::getKey)
        .collect(Collectors.toList());
}

Più "generico" e il più sicuro possibile

/**
 * Find any key matching the value, in the given map.
 *
 * @param mapOrNull Any map, null is considered a valid value.
 * @param value     The value to be searched.
 * @param <K>       Type of the key.
 * @param <T>       Type of the value.
 * @return An optional containing a key, if found.
 */
public static <K, T> Optional<K> getKey(Map<K, T> mapOrNull, T value) {
    return Optional.ofNullable(mapOrNull).flatMap(map -> map.entrySet()
            .stream()
            .filter(e -> Objects.equals(e.getValue(), value))
            .map(Map.Entry::getKey)
            .findAny());
}

O se sei su JDK7.

private String getKey(Integer value){
    for(String key : team1.keySet()){
        if(Objects.equals(team1.get(key), value)){
            return key; //return the first found
        }
    }
    return null;
}

private List<String> getKeys(Integer value){
   List<String> keys = new ArrayList<String>();
   for(String key : team1.keySet()){
        if(Objects.equals(team1.get(key), value)){
             keys.add(key);
      }
   }
   return keys;
}

2
Ma cosa succede se più chiavi corrispondono allo stesso valore? dovresti invece restituire un elenco di chiavi
— Óscar López,

@ ÓscarLópez Non possono. HashMaple chiavi sono uniche.
— Marchese di Lorne,

6

Puoi recuperare tutte le Mapchiavi usando il metodo keySet(). Ora, se ciò di cui hai bisogno è ottenere una chiave dato il suo valore , è una questione completamente diversa e Mapnon ti aiuterà lì; avresti bisogno di una struttura di dati specializzata, come BidiMap(una mappa che consenta la ricerca bidirezionale tra chiave e valori) dalle Collezioni Commons di Apache - sappi anche che diverse chiavi diverse potrebbero essere mappate sullo stesso valore.



1

Se hai solo bisogno di qualcosa di semplice e di più di una verifica.

public String getKey(String key)
{
    if(map.containsKey(key)
    {
        return key;
    }
    return null;
}

Quindi puoi cercare qualsiasi chiave.

System.out.println( "Does this key exist? : " + getKey("United") );

1
Questo metodo è totalmente ridondante.
— Marchese di Lorne,

1
private Map<String, Integer> _map= new HashMap<String, Integer>();
Iterator<Map.Entry<String,Integer>> itr=  _map.entrySet().iterator();
                //please check 
                while(itr.hasNext())
                {
                    System.out.println("key of : "+itr.next().getKey()+" value of      Map"+itr.next().getValue());
                }

Non funziona Chiaramente non l'hai provato. Chiamare next()due volte nel ciclo significa che si stamperanno i tasti dispari insieme ai valori pari.
— Marchese di Lorne,

0

Utilizzare il funzionamento funzionale per un'iterazione più rapida.

team1.keySet().forEach((key) -> { System.out.println(key); });


-1

Una soluzione può essere, se si conosce la posizione della chiave, convertire le chiavi in ​​un array String e restituire il valore nella posizione:

public String getKey(int pos, Map map) {
    String[] keys = (String[]) map.keySet().toArray(new String[0]);

    return keys[pos];
}

Niente di sapere l'indice nella domanda.
— Marchese di Lorne,

-2

Prova questo semplice programma:

public class HashMapGetKey {

public static void main(String args[]) {

      // create hash map

       HashMap map = new HashMap();

      // populate hash map

      map.put(1, "one");
      map.put(2, "two");
      map.put(3, "three");
      map.put(4, "four");

      // get keyset value from map

Set keyset=map.keySet();

      // check key set values

      System.out.println("Key set values are: " + keyset);
   }    
}

-2
public class MyHashMapKeys {

    public static void main(String a[]){
        HashMap<String, String> hm = new HashMap<String, String>();
        //add key-value pair to hashmap
        hm.put("first", "FIRST INSERTED");
        hm.put("second", "SECOND INSERTED");
        hm.put("third","THIRD INSERTED");
        System.out.println(hm);
        Set<String> keys = hm.keySet();
        for(String key: keys){
            System.out.println(key);
        }
    }
}

Copia solo le risposte esistenti. -1
— james.garriss

-2

Per ottenere le chiavi in ​​HashMap, abbiamo il metodo keySet () che è presente nel java.util.Hashmappacchetto. es:

Map<String,String> map = new Hashmap<String,String>();
map.put("key1","value1");
map.put("key2","value2");

// Now to get keys we can use keySet() on map object
Set<String> keys = map.keySet();

Ora le chiavi avranno tutte le chiavi disponibili nella mappa. es: [chiave1, chiave2]


java,util.HashMapè una classe, non un pacchetto, e non c'è nulla qui che non fosse qui cinque anni fa.
— Marchese di Lorne,

-3

Quello che farò, che è molto semplice, ma sprecare la memoria è mappare i valori con una chiave e fare l'opposto per mappare le chiavi con un valore facendo questo:

private Map<Object, Object> team1 = new HashMap<Object, Object>();

è importante che tu usi in <Object, Object>modo da poter mappare keys:Valuee Value:Keyscosì

team1.put("United", 5);

team1.put(5, "United");

Quindi se usi team1.get("United") = 5eteam1.get(5) = "United"

Ma se usi un metodo specifico su uno degli oggetti nelle coppie, sarò meglio se crei un'altra mappa:

private Map<String, Integer> team1 = new HashMap<String, Integer>();

private Map<Integer, String> team1Keys = new HashMap<Integer, String>();

e poi

team1.put("United", 5);

team1Keys.put(5, "United");

e ricorda, mantienilo semplice;)


-3

Per ottenere la chiave e il suo valore

per esempio

private Map<String, Integer> team1 = new HashMap<String, Integer>();
  team1.put("United", 5);
  team1.put("Barcelona", 6);
    for (String key:team1.keySet()){
                     System.out.println("Key:" + key +" Value:" + team1.get(key)+" Count:"+Collections.frequency(team1, key));// Get Key and value and count
                }

Stampa: Chiave: United Valore: 5 Chiave: Barcelona Valore: 6

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.