2012-05-05 22 views
96

Ho un HashMap in Java in questo modo:Prendi le chiavi dal HashMap in Java

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

Poi riempire in questo modo:

team1.put("United", 5); 

Come posso ottenere le chiavi? Qualcosa come: team1.getKey() per restituire "United".

+8

Una mappa contiene diverse chiavi. È un dizionario. La tua domanda non ha senso. –

+0

Cosa ti aspetti che 'team1.getKey()' restituisca se: (1) la mappa è vuota, o (2) se contiene più chiavi? – NPE

+0

'int' dovrebbe essere usato per singoli come questo. –

risposta

205

A HashMap contiene più di una chiave. È possibile utilizzare keySet() per ottenere l'insieme di tutte le chiavi.

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

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

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

stamperà "foo" e "bar".

+0

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

+0

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

+10

Qual è il punto di una mappa con una singola chiave? Crea una classe con un campo chiave e un campo valore. –

5

È possibile recuperare tutte le chiavi Map utilizzando il metodo keySet(). Ora, se quello che ti serve è ottenere una chiave dato il suo valore , è una questione completamente diversa e Map non ti aiuterà; avresti bisogno di una struttura dati specializzata, come BidiMap (una mappa che consente la ricerca bidirezionale tra chiave e valori) da Apache Commons Collections - anche essere consapevoli del fatto che diverse chiavi potrebbero essere mappate allo stesso valore.

18

Verificare questo.

http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html

Supponendo di avere un valore diverso per ogni tasto, si può fare qualcosa di simile:

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

Oppure, se non si può assumere che ogni tasto ha un valore differente:

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

o utilizzando JDK8

private Optional<String> getKey(Integer value){ 
    return team1 
     .entrySet() 
     .stream() 
     .filter(e -> e.getValue().equals(value)) 
     .map(e -> e.getKey()) 
     .findFirst(); 
} 

private List<String> getKeys(Integer value){ 
    return team1 
     .entrySet() 
     .stream() 
     .filter(e -> e.getValue().equals(value)) 
     .map(e -> e.getKey()) 
     .collect(Collectors.toList()); 
} 
+0

Ma cosa succede se più chiavi si associano allo stesso valore? dovresti restituire un elenco di chiavi invece –

0

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

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

Quindi è possibile cercare qualsiasi tasto.

System.out.println("Does this key exist? : " + getKey("United")); 
2
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()); 
       } 
-1

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); 
    }  
} 
-1
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); 
     } 
    } 
} 
+0

Copia semplicemente le risposte esistenti. -1 –

26

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

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

keySet() restituisce una lista, quindi tu converti la lista a un array.

Il problema, ovviamente, è che un set non promette di mantenere l'ordine. Se hai solo un oggetto nella tua HashMap, sei bravo, ma se ne hai di più, è meglio andare sulla mappa, come hanno fatto altre risposte.

+0

Mi ha aiutato anche :) – sTg

-2

quello che farò, che è molto semplice, ma la memoria dei rifiuti è quello di mappare i valori con una chiave e fare l'oposite per mappare i tasti con un valore rendendo questo:

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

è importante che si utilizza <Object, Object> in modo da poter mappare keys:Value e Value:Keys come questo

team1.put("United", 5);

team1.put(5, "United");

Quindi, se si utilizza team1.get("United") = 5 e team1.get(5) = "United"

Ma se si utilizza un metodo specifico su uno degli oggetti nelle coppie starò meglio se si effettua 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 ricordare, mantenere le cose semplici;)

-1

Per ottenere chiave e il suo valore

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 
       } 

stamperà: chiave: Valore Unito: 5 Chiave: Barcelona Valore: 6