Java Hashmap: ¿Cómo obtener la clave del valor?


Si tengo el valor "foo", y HashMap<String> ftw para que ftw.containsValue("foo") devuelve true, ¿cómo puedo obtener la clave correspondiente? ¿Tengo que recorrer el hashmap? ¿Cuál es la mejor manera de hacerlo?

 380
Author: Nick Heiner, 2009-09-05

30 answers

Si elige usar la biblioteca Commons Collections en lugar de la API estándar de colecciones Java, puede lograr esto con facilidad.

La interfaz BidiMap en la biblioteca de Colecciones es un mapa bidireccional, que le permite asignar una clave a un valor (como mapas normales), y también asignar un valor a una clave, lo que le permite realizar búsquedas en ambas direcciones. La obtención de una clave para un valor es soportada por el método getKey () .

Hay una advertencia sin embargo, los mapas bidi no pueden tener varios valores asignados a claves y, por lo tanto, a menos que su conjunto de datos tenga asignaciones 1:1 entre claves y valores, no puede usar mapas bidimensionales.

Actualización

Si desea confiar en la API de Java Collections, tendrá que garantizar la relación 1:1 entre las claves y los valores en el momento de insertar el valor en el mapa. Esto es más fácil decirlo que hacerlo.

Una vez que pueda asegurarse de que, utilice el método entrySet () para obtener el conjunto de entradas (asignaciones) en el mapa. Una vez que haya obtenido el conjunto cuyo tipo es Map.Entry , itere a través de las entradas, comparando el valor almacenado con el esperado, y obtenga la clave correspondiente.

Actualizar #2

El soporte para mapas bidi con genéricos se puede encontrar en Google Guava y las bibliotecas refactorizadas Commons-Collections (esta última no es un proyecto Apache). Gracias a Esko por señalar a los desaparecidos soporte genérico en Colecciones Apache Commons. El uso de colecciones con genéricos hace que el código sea más fácil de mantener.

 195
Author: Vineet Reynolds,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-28 21:14:45

Si su estructura de datos tiene muchos a uno mapeo entre claves y valores, debe iterar sobre las entradas y elegir todas las claves adecuadas:

public static <T, E> Set<T> getKeysByValue(Map<T, E> map, E value) {
    Set<T> keys = new HashSet<T>();
    for (Entry<T, E> entry : map.entrySet()) {
        if (Objects.equals(value, entry.getValue())) {
            keys.add(entry.getKey());
        }
    }
    return keys;
}

En el caso de relación uno a uno, puede devolver la primera clave coincidente:

public static <T, E> T getKeyByValue(Map<T, E> map, E value) {
    for (Entry<T, E> entry : map.entrySet()) {
        if (Objects.equals(value, entry.getValue())) {
            return entry.getKey();
        }
    }
    return null;
}

En Java 8:

public static <T, E> Set<T> getKeysByValue(Map<T, E> map, E value) {
    return map.entrySet()
              .stream()
              .filter(entry -> Objects.equals(entry.getValue(), value))
              .map(Map.Entry::getKey)
              .collect(Collectors.toSet());
}

También, para los usuarios de Guayaba, BiMap puede ser útil. Por ejemplo:

BiMap<Token, Character> tokenToChar = 
    ImmutableBiMap.of(Token.LEFT_BRACKET, '[', Token.LEFT_PARENTHESIS, '(');
Token token = tokenToChar.inverse().get('(');
Character c = tokenToChar.get(token);
 559
Author: Vitalii Fedorenko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-25 04:40:58
public class NewClass1 {

    public static void main(String[] args) {
       Map<Integer, String> testMap = new HashMap<Integer, String>();
        testMap.put(10, "a");
        testMap.put(20, "b");
        testMap.put(30, "c");
        testMap.put(40, "d");
        for (Entry<Integer, String> entry : testMap.entrySet()) {
            if (entry.getValue().equals("c")) {
                System.out.println(entry.getKey());
            }
        }
    }
}

Algo de información adicional... Puede serle útil

El método anterior puede no ser bueno si tu hashmap es realmente grande. Si su hashmap contiene una asignación de clave única a valor único, puede mantener otro hashmap que contenga la asignación de valor a clave.

Es decir, tienes que mantener dos hashmaps

1. Key to value

2. Value to key 

En ese caso, puede usar el segundo hashmap para obtener la clave.

 70
Author: Fathah Rehman P,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-02 05:54:28

Puede insertar tanto la clave, el par de valores como su inversa en la estructura de su mapa

map.put("theKey", "theValue");
map.put("theValue", "theKey");

Usando map.get ("theValue") devolverá entonces"theKey".

Es una manera rápida y sucia que he hecho mapas constantes, que solo funcionarán para unos pocos conjuntos de datos seleccionados:

  • Contiene solo 1 a 1 pares
  • El conjunto de valores es disjunto del conjunto de claves (1->2, 2->3 lo rompe)
 19
Author: Chicowitz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-04 00:42:41

Creo que sus opciones son

  • Use una implementación de mapa construida para esto, como el BiMap de google collections. Tenga en cuenta que el BiMap de Google collections requiere uniqueless de valores, así como claves, pero proporciona un alto rendimiento en ambas direcciones rendimiento
  • Mantener manualmente dos mapas-uno para clave - > valor, y otro mapa para valor - > clave
  • Itere a través de la entrySet() y para encontrar las claves que coinciden con el valor. Este es el método más lento, ya que requiere iterar a través de toda la colección, mientras que los otros dos métodos no requieren eso.
 17
Author: Chi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-28 21:30:53

Para encontrar todas las claves que se asignan a ese valor, itere a través de todos los pares en el hashmap, utilizando map.entrySet().

 11
Author: wsorenson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-04 12:23:02

No hay una respuesta inequívoca, porque varias claves pueden asignarse al mismo valor. Si está imponiendo la singularidad con su propio código, la mejor solución es crear una clase que use dos Hashmaps para rastrear las asignaciones en ambas direcciones.

 10
Author: recursive,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-09-05 17:08:57

Decora el mapa con tu propia implementación

class MyMap<K,V> extends HashMap<K, V>{

    Map<V,K> reverseMap = new HashMap<V,K>();

    @Override
    public V put(K key, V value) {
        // TODO Auto-generated method stub
        reverseMap.put(value, key);
        return super.put(key, value);
    }

    public K getKey(V value){
        return reverseMap.get(value);
    }
}
 10
Author: ABHI,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-23 13:45:03

Creo que esta es la mejor solución, dirección original: Java2s

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

        public class Main {

          public static void main(String[] argv) {
            Map<String, String> map = new HashMap<String, String>();
            map.put("1","one");
            map.put("2","two");
            map.put("3","three");
            map.put("4","four");

            System.out.println(getKeyFromValue(map,"three"));
          }


// hm is the map you are trying to get value from it
          public static Object getKeyFromValue(Map hm, Object value) {
            for (Object o : hm.keySet()) {
              if (hm.get(o).equals(value)) {
                return o;
              }
            }
            return null;
          }
        }

Un uso fácil: si pones todos los datos en hasMap y tienes item = "Automobile", entonces estás buscando su clave en HashMap. esa es una buena solución.

getKeyFromValue(hashMap, item);
System.out.println("getKeyFromValue(hashMap, item): "+getKeyFromValue(hashMap, item));
 8
Author: boy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-22 06:21:55

Si construye el mapa en su propio código, intente juntar la clave y el valor en el mapa:

public class KeyValue {
    public Object key;
    public Object value;
    public KeyValue(Object key, Object value) { ... }
}

map.put(key, new KeyValue(key, value));

Entonces cuando tienes un valor, también tienes la clave.

 7
Author: David Tinker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-09-05 17:58:54

Me temo que solo tendrás que iterar tu mapa. Más corto que podría llegar a:

Iterator<Map.Entry<String,String>> iter = map.entrySet().iterator();
while (iter.hasNext()) {
    Map.Entry<String,String> entry = iter.next();
    if (entry.getValue().equals(value_you_look_for)) {
        String key_you_look_for = entry.getKey();
    }
}
 6
Author: André van Toly,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-05-28 09:52:58
for(int key: hm.keySet()) {
    if(hm.get(key).equals(value)) {
        System.out.println(key); 
    }
}
 6
Author: user309309,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-05 12:35:07

Parece que la mejor manera es iterar sobre las entradas usando map.entrySet() ya que map.containsValue() probablemente hace esto de todos modos.

 6
Author: Jonas Klemming,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-22 06:11:34

Usando Java 8:

ftw.forEach((key, value) -> {
    if (value=="foo") {
        System.out.print(key);
    }
});
 5
Author: phani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-09 10:32:04

Para Android Development targeting API Objects.equals no está implementado. Aquí hay una alternativa simple:

public <K, V> K getKeyByValue(Map<K, V> map, V value) {
    for (Map.Entry<K, V> entry : map.entrySet()) {
            if (value.equals(entry.getValue())) {
            return entry.getKey();
        }
    }
    return null;
}
 5
Author: The Berga,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-14 14:14:31

Puedes usar lo siguiente:

public class HashmapKeyExist {
    public static void main(String[] args) {
        HashMap<String, String> hmap = new HashMap<String, String>();
        hmap.put("1", "Bala");
        hmap.put("2", "Test");

        Boolean cantain = hmap.containsValue("Bala");
        if(hmap.containsKey("2") && hmap.containsValue("Test"))
        {
            System.out.println("Yes");
        }
        if(cantain == true)
        {
            System.out.println("Yes"); 
        }

        Set setkeys = hmap.keySet();
        Iterator it = setkeys.iterator();

        while(it.hasNext())
        {
            String key = (String) it.next();
            if (hmap.get(key).equals("Bala"))
            {
                System.out.println(key);
            }
        }
    }
}
 3
Author: Balasubramanian Ganapathi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-09 23:24:22

Puede obtener la clave usando valores usando el siguiente código..

ArrayList valuesList = new ArrayList();
Set keySet = initalMap.keySet();
ArrayList keyList = new ArrayList(keySet);

for(int i = 0 ; i < keyList.size() ; i++ ) {
    valuesList.add(initalMap.get(keyList.get(i)));
}

Collections.sort(valuesList);
Map finalMap = new TreeMap();
for(int i = 0 ; i < valuesList.size() ; i++ ) {
    String value = (String) valuesList.get(i);

    for( int j = 0 ; j < keyList.size() ; j++ ) {
        if(initalMap.get(keyList.get(j)).equals(value)) {
            finalMap.put(keyList.get(j),value);
        }   
    }
}
System.out.println("fianl map ---------------------->  " + finalMap);
 2
Author: Amit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-12 14:26:58
public static class SmartHashMap <T1 extends Object, T2 extends Object> {
    public HashMap<T1, T2> keyValue;
    public HashMap<T2, T1> valueKey;

    public SmartHashMap(){
        this.keyValue = new HashMap<T1, T2>();
        this.valueKey = new HashMap<T2, T1>();
    }

    public void add(T1 key, T2 value){
        this.keyValue.put(key, value);
        this.valueKey.put(value, key);
    }

    public T2 getValue(T1 key){
        return this.keyValue.get(key);
    }

    public T1 getKey(T2 value){
        return this.valueKey.get(value);
    }

}
 2
Author: margus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-12 20:24:54
public static String getKey(Map<String, Integer> mapref, String value) {
    String key = "";
    for (Map.Entry<String, Integer> map : mapref.entrySet()) {
        if (map.getValue().toString().equals(value)) {
            key = map.getKey();
        }
    }
    return key;
}
 2
Author: Amazing India,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-22 07:34:51

Sí, tiene que recorrer el hashmap, a menos que implemente algo en la línea de lo que sugieren estas diversas respuestas. En lugar de jugar con el entrySet, me acaba de obtener el keySet(), iterar sobre ese conjunto, y mantener la (primera) clave que obtiene su valor coincidente. Si necesitas todas las claves que coincidan con ese valor, obviamente tienes que hacerlo todo.

Como Jonas sugiere, esto podría ser lo que ya está haciendo el método containsValue, por lo que podría omitirlo pruebe todos juntos, y simplemente haga la iteración cada vez (o tal vez el compilador ya eliminará la redundancia, quién sabe).

También, en relación con las otras respuestas, si su mapa inverso se parece a

Map<Value, Set<Key>>

Puede tratar con asignaciones de clave->valor no únicas, si necesita esa capacidad (desenredándolas a un lado). Eso incorporaría bien en cualquiera de las soluciones que la gente sugiere aquí usando dos mapas.

 1
Author: Carl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-09-05 19:45:31
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

public class ValueKeysMap<K, V> extends HashMap <K,V>{
    HashMap<V, Set<K>> ValueKeysMap = new HashMap<V, Set<K>>();

    @Override
    public boolean containsValue(Object value) {
        return ValueKeysMap.containsKey(value);
    }

    @Override
    public V put(K key, V value) {
        if (containsValue(value)) {
            Set<K> keys = ValueKeysMap.get(value);
            keys.add(key);
        } else {
            Set<K> keys = new HashSet<K>();
            keys.add(key);
            ValueKeysMap.put(value, keys);
        }
        return super.put(key, value);
    }

    @Override
    public V remove(Object key) {
        V value = super.remove(key);
        Set<K> keys = ValueKeysMap.get(value);
        keys.remove(key);
        if(keys.size() == 0) {
           ValueKeysMap.remove(value);
        }
        return value;
    }

    public Set<K> getKeys4ThisValue(V value){
        Set<K> keys = ValueKeysMap.get(value);
        return keys;
    }

    public boolean valueContainsThisKey(K key, V value){
        if (containsValue(value)) {
            Set<K> keys = ValueKeysMap.get(value);
            return keys.contains(key);
        }
        return false;
    }

    /*
     * Take care of argument constructor and other api's like putAll
     */
}
 1
Author: Kanagavelu Sugumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-25 06:06:54
/**
 * This method gets the Key for the given Value
 * @param paramName
 * @return
 */
private String getKeyForValueFromMap(String paramName) {
    String keyForValue = null;
    if(paramName!=null)) {
        Set<Entry<String,String>> entrySet = myMap().entrySet();
        if(entrySet!=null && entrySet.size>0) {
            for(Entry<String,String> entry : entrySet) {
                if(entry!=null && paramName.equalsIgnoreCase(entry.getValue())) {
                    keyForValue = entry.getKey();
                }
            }
        }
    }
    return keyForValue;
}
 1
Author: kanaparthikiran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-22 05:56:27
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class M{
public static void main(String[] args) {

        HashMap<String, List<String>> resultHashMap = new HashMap<String, List<String>>();

        Set<String> newKeyList = resultHashMap.keySet();


        for (Iterator<String> iterator = originalHashMap.keySet().iterator(); iterator.hasNext();) {
            String hashKey = (String) iterator.next();

            if (!newKeyList.contains(originalHashMap.get(hashKey))) {
                List<String> loArrayList = new ArrayList<String>();
                loArrayList.add(hashKey);
                resultHashMap.put(originalHashMap.get(hashKey), loArrayList);
            } else {
                List<String> loArrayList = resultHashMap.get(originalHashMap
                        .get(hashKey));
                loArrayList.add(hashKey);
                resultHashMap.put(originalHashMap.get(hashKey), loArrayList);
            }
        }

        System.out.println("Original HashMap : " + originalHashMap);
        System.out.println("Result HashMap : " + resultHashMap);
    }
}
 1
Author: Madhav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-20 10:40:12

Use una envoltura delgada: HMap

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class HMap<K, V> {

   private final Map<K, Map<K, V>> map;

   public HMap() {
      map = new HashMap<K, Map<K, V>>();
   }

   public HMap(final int initialCapacity) {
      map = new HashMap<K, Map<K, V>>(initialCapacity);
   }

   public boolean containsKey(final Object key) {
      return map.containsKey(key);
   }

   public V get(final Object key) {
      final Map<K, V> entry = map.get(key);
      if (entry != null)
         return entry.values().iterator().next();
      return null;
   }

   public K getKey(final Object key) {
      final Map<K, V> entry = map.get(key);
      if (entry != null)
         return entry.keySet().iterator().next();
      return null;
   }

   public V put(final K key, final V value) {
      final Map<K, V> entry = map
            .put(key, Collections.singletonMap(key, value));
      if (entry != null)
         return entry.values().iterator().next();
      return null;
   }
}
 1
Author: Jayen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-22 06:27:21

Mis 2 centavos. Puede obtener las claves en una matriz y luego recorrer la matriz. Esto afectará el rendimiento de este bloque de código si el mapa es bastante grande, donde está obteniendo las claves en una matriz primero que podría consumir algún tiempo y luego está en bucle. De lo contrario, para mapas más pequeños debería estar bien.

String[] keys =  yourMap.keySet().toArray(new String[0]);

for(int i = 0 ; i < keys.length ; i++){
    //This is your key    
    String key = keys[i];

    //This is your value
    yourMap.get(key)            
}
 1
Author: Manu Bhat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-05 13:20:35

Si bien esto no responde directamente a la pregunta, está relacionado.

De esta manera no necesitas seguir creando/iterando. Simplemente cree un mapa inverso una vez y obtenga lo que necesita.

/**
 * Both key and value types must define equals() and hashCode() for this to work.
 * This takes into account that all keys are unique but all values may not be.
 *
 * @param map
 * @param <K>
 * @param <V>
 * @return
 */
public static <K, V> Map<V, List<K>> reverseMap(Map<K,V> map) {
    if(map == null) return null;

    Map<V, List<K>> reverseMap = new ArrayMap<>();

    for(Map.Entry<K,V> entry : map.entrySet()) {
        appendValueToMapList(reverseMap, entry.getValue(), entry.getKey());
    }

    return reverseMap;
}


/**
 * Takes into account that the list may already have values.
 * 
 * @param map
 * @param key
 * @param value
 * @param <K>
 * @param <V>
 * @return
 */
public static <K, V> Map<K, List<V>> appendValueToMapList(Map<K, List<V>> map, K key, V value) {
    if(map == null || key == null || value == null) return map;

    List<V> list = map.get(key);

    if(list == null) {
        List<V> newList = new ArrayList<>();
        newList.add(value);
        map.put(key, newList);
    }
    else {
        list.add(value);
    }

    return map;
}
 1
Author: Markymark,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-01 23:22:05

En java8

map.entrySet().stream().filter(entry -> entry.getValue().equals(value))
    .forEach(entry -> System.out.println(entry.getKey()));
 0
Author: user3724331,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-10 01:53:11

Es importante tener en cuenta que desde esta pregunta, Apache Collections soporta BidiMaps genéricos. Así que algunas de las respuestas más votadas ya no son precisas en ese punto.

Para un BidiMap serializado que también admite valores duplicados ( escenario de 1 a muchos ) también considere MapDB.org .

 0
Author: kervin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-31 16:25:49
  1. Si desea obtener clave de valor, es mejor usar bidimap (mapas bidireccionales) , puede obtener clave de valor en O(1) tiempo.

    Pero, el inconveniente con esto es que solo puede usar un conjunto de claves y un conjunto de valores únicos.

  2. Hay una estructura de datos llamada Tabla en java, que no es más que un mapa de mapas como

    Table == map >

    Aquí puede obtener map<B,C> consultando T.row(a);, y también puede obtener map<A,C> consultando T.column(b);

En su caso especial, inserte C como una constante.

Por lo tanto, como ,...

Entonces, si encuentra via T. row(a1) ---> devuelve mapa de get> get keyset este mapa devuelto.

Si necesita encontrar el valor de la clave, entonces, T. column(b2) returns> devuelve el mapa de get> obtener el conjunto de claves del mapa devuelto.

Ventajas sobre el caso anterior:

  1. Puede usar múltiples valores.
  2. Más eficiente al usar grandes conjuntos de datos.
 0
Author: Batman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-07 15:06:25

Creo que keySet()puede ser bueno encontrar las claves que se asignan al valor, y tener un mejor estilo de codificación que entrySet().

Ex:

Supongamos que usted tiene un HashMap map, ArrayList res, a valor desea encontrar todos la tecla asignación para , a continuación, almacenar las claves para el res.

Puede escribir el código a continuación:

    for (int key : map.keySet()) {
        if (map.get(key) == value) {
            res.add(key);
        }
    }

En lugar de usar entrySet() abajo:

    for (Map.Entry s : map.entrySet()) {
        if ((int)s.getValue() == value) {
            res.add((int)s.getKey());
        }
    }

Espero que ayude:)

 0
Author: FrancisGeek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-08 13:55:04