Java Hashmap: How to get key from value?

前端 未结 30 2345
忘掉有多难
忘掉有多难 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:08

    You can use the below:

    public class HashmapKeyExist {
        public static void main(String[] args) {
            HashMap hmap = new HashMap();
            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);
                }
            }
        }
    }
    

提交回复
热议问题