Java Hashmap: How to get key from value?

前端 未结 30 1853
忘掉有多难
忘掉有多难 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条回答
  •  -上瘾入骨i
    2020-11-22 03:11

    You can get the key using values using following code..

    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);
    

提交回复
热议问题