Java Hashmap: How to get key from value?

前端 未结 30 2263
忘掉有多难
忘掉有多难 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条回答
  •  Happy的楠姐
    2020-11-22 03:17

    public class NewClass1 {
    
        public static void main(String[] args) {
           Map testMap = new HashMap();
            testMap.put(10, "a");
            testMap.put(20, "b");
            testMap.put(30, "c");
            testMap.put(40, "d");
            for (Entry 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.

提交回复
热议问题