Java Hashmap: How to get key from value?

前端 未结 30 1887
忘掉有多难
忘掉有多难 2020-11-22 02:14

If I have the value \"foo\", and a HashMap ftw for which ftw.containsValue(\"foo\") returns true, how can I

相关标签:
30条回答
  • 2020-11-22 03:11

    In java8

    map.entrySet().stream().filter(entry -> entry.getValue().equals(value))
        .forEach(entry -> System.out.println(entry.getKey()));
    
    0 讨论(0)
  • 2020-11-22 03:14

    Yes, you have to loop through the hashmap, unless you implement something along the lines of what these various answers suggest. Rather than fiddling with the entrySet, I'd just get the keySet(), iterate over that set, and keep the (first) key that gets you your matching value. If you need all the keys that match that value, obviously you have to do the whole thing.

    As Jonas suggests, this might already be what the containsValue method is doing, so you might just skip that test all-together, and just do the iteration every time (or maybe the compiler will already eliminate the redundancy, who knows).

    Also, relative to the other answers, if your reverse map looks like

    Map<Value, Set<Key>>
    

    you can deal with non-unique key->value mappings, if you need that capability (untangling them aside). That would incorporate fine into any of the solutions people suggest here using two maps.

    0 讨论(0)
  • 2020-11-22 03:15

    My 2 cents. You can get the keys in an array and then loop through the array. This will affect performance of this code block if the map is pretty big , where in you are getting the keys in an array first which might consume some time and then you are looping. Otherwise for smaller maps it should be ok.

    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)            
    }
    
    0 讨论(0)
  • 2020-11-22 03:17
    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());
                }
            }
        }
    }
    

    Some additional info... May be useful to you

    Above method may not be good if your hashmap is really big. If your hashmap contain unique key to unique value mapping, you can maintain one more hashmap that contain mapping from Value to Key.

    That is you have to maintain two hashmaps

    1. Key to value
    
    2. Value to key 
    

    In that case you can use second hashmap to get key.

    0 讨论(0)
  • 2020-11-22 03:17

    I'm afraid you'll just have to iterate your map. Shortest I could come up with:

    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();
        }
    }
    
    0 讨论(0)
  • 2020-11-22 03:17

    While this does not directly answer the question, it is related.

    This way you don't need to keep creating/iterating. Just create a reverse map once and get what you need.

    /**
     * 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;
    }
    
    0 讨论(0)
提交回复
热议问题