2012-05-05 25 views
96

Tengo un Hashmap en Java como esto:Obtener claves de HashMap en Java

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

Entonces me llenan de esta manera:

team1.put("United", 5); 

¿Cómo puedo conseguir las llaves? Algo como: team1.getKey() para devolver "United".

+8

Un mapa contiene varias claves. Es un diccionario. Tu pregunta no tiene sentido. –

+0

¿Qué espera 'team1.getKey()' para devolver si: (1) el mapa está vacío, o (2) si contiene varias claves? – NPE

+0

'int' se debe utilizar para los únicos como este. –

Respuesta

205

A HashMap contiene más de una clave. Puede usar keySet() para obtener el conjunto de todas las claves.

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

almacenará 1 con llave "foo" y 2 con llave "bar". Para iterar sobre todas las teclas:

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

imprimirá "foo" y "bar".

+0

Pero en este caso solo tengo una clave para cada valor. No es posible escribir algo como team1.getKey()? – masb

+0

No tienes un mapa con un elemento. Pero es un mapa: una estructura que puede contener más de un elemento. – Matteo

+10

¿Qué sentido tiene un mapa con una sola clave? Crea una clase con un campo clave y un campo de valor. –

5

Puede recuperar todas las claves Map usando el método keySet(). Ahora, si lo que necesita es obtener una clave dado su valor, esa es una cuestión totalmente diferente y Map no lo ayudará allí; necesitaría una estructura de datos especializada, como BidiMap (un mapa que permite la búsqueda bidireccional entre clave y valores) desde Apache's Commons Collections - también tenga en cuenta que varias claves diferentes podrían asignarse al mismo valor.

18

Mira esto.

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

Asumiendo que usted tiene un valor diferente para cada tecla, se puede hacer algo como esto:

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

O si no se puede asumir que cada tecla tiene un valor 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 usando 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

¿Pero qué ocurre si varias teclas se asignan al mismo valor? Debería devolver una lista de claves en su lugar –

0

Si solo necesitas algo simple y más de una verificación.

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

A continuación, puede buscar cualquier tecla.

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

Prueba este sencillo programa:

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

. Simplemente copia las respuestas existentes. -1 –

26

Esto es factible, al menos en teoría, si que conocer el índice:

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

keySet() devuelve una lista, por lo que se convierte la lista a una matriz.

El problema, por supuesto, es que un conjunto no promete mantener su pedido. Si solo tiene un elemento en su HashMap, está bien, pero si tiene más que eso, es mejor recorrer el mapa, como lo han hecho otras respuestas.

+0

me ayudó a mí también :) – sTg

-2

Lo que haré lo cual es muy simple, pero la memoria de residuos es mapear los valores con una llave y hacer lo opuesto a mapear las teclas con un valor de hacer esto:

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

es importante que utiliza <Object, Object> para que pueda mapear keys:Value y Value:Keys como esto

team1.put("United", 5);

team1.put(5, "United");

tanto, si utiliza team1.get("United") = 5 y team1.get(5) = "United"

Pero si se utiliza algún método específico en una de los objetos en los pares estaré mejor si haces otro mapa:

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

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

y luego

team1.put("United", 5);

team1Keys.put(5, "United");

y recordar, que sea sencillo;)

-1

Para obtener clave y su valor

por ejemplo

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 
       } 

imprimirá: clave: Valor Unido: 5 Clave: Barcelona Valor: 6

Cuestiones relacionadas