如果我有值“foo”,和一个HashMap<String> ftw,其中ftw. containsvalue(“foo”)返回真,我怎么能得到相应的键?我需要遍历hashmap吗?最好的方法是什么?


当前回答

听起来最好的方法是使用map.entrySet()来遍历条目,因为map.containsValue()可能会这样做。

其他回答

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

一些额外的信息…可能对你有用

如果你的hashmap真的很大,上面的方法可能不太好。如果您的hashmap包含唯一键到唯一值的映射,您可以维护一个包含从值到键映射的hashmap。

也就是说你必须维护两个hashmap

1. Key to value

2. Value to key 

在这种情况下,您可以使用第二个hashmap来获取key。

试试这个:

static String getKeyFromValue(LinkedHashMap<String, String> map,String value) {
    for (int x=0;x<map.size();x++){
        if( String.valueOf( (new ArrayList<String>(map.values())).get(x) ).equals(value))
            return String.valueOf((new ArrayList<String>(map.keySet())).get(x));
    }
    return null;
}

你也可以这样做: 第一个:put map (key, value) 第二:更新键需要删除表达式 第三:和oldValue一起放一个新键

从Map中获取给定值的键的最简单实用方法:

public static void fetchValue(Map<String, Integer> map, Integer i)
{   
Stream stream = map.entrySet().stream().filter(val-> val.getValue().equals(i)).map(Map.Entry::getKey);
stream.forEach(System.out::println);    
}

详细解释:

方法fetchValue接受映射,该映射的键是String,值是Integer。 然后使用entryset().stream()将结果转换为流。 接下来,我们使用过滤器(中间操作),它会给我们一个等于第二个参数的值。 最后,我们使用forEach(最终操作)来打印最终结果。

用你自己的实现来装饰地图

class MyMap<K,V> extends HashMap<K, V>{

    Map<V,K> reverseMap = new HashMap<V,K>();

    @Override
    public V put(K key, V value) {
        // TODO Auto-generated method stub
        reverseMap.put(value, key);
        return super.put(key, value);
    }

    public K getKey(V value){
        return reverseMap.get(value);
    }
}