Java Hashmap: How to get key from value?

前端 未结 30 2222
忘掉有多难
忘掉有多难 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: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)            
    }
    

提交回复
热议问题