在哈希表中找到值时打印键

时间:2013-03-03 09:11:09

标签: java hashmap hashtable

我正在尝试在找到或存在值时在哈希表中打印键值。这段代码似乎不起作用。

    Map<String,Integer> map = new HashMap<String, Integer>();
    for(int j=0;j<al.size();j++){            
        Integer count = map.get(al.get(j));       
        map.put(al.get(j), count==null?1:count+1);   //auto boxing and count

    }
    int max = Collections.max(map.values());
    if( map.containsValue(max))
    {

     System.out.println(map.keySet());
    }

1 个答案:

答案 0 :(得分:2)

首先,值可能会发生多次次 - 我假设您要打印所有匹配键?

其次,哈希表基本上不是为按值查找而设计的 - 所以你必须迭代所有条目:

// Adjust types accordingly
for (Map.Entry<String, String> entry : map.entrySet()) {
    if (entry.getValue().equals(targetValue)) {
        System.out.println(entry.getKey());
    }
}

如果某些值可能为空,则应更改相等性检查。

相关问题