【问题标题】:Printing key when value is found in hash table在哈希表中找到值时打印键
【发布时间】:2013-03-03 09:11:09
【问题描述】:

当找到或存在值时,我试图在哈希表中打印键值。此代码似乎不起作用。

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

【问题讨论】:

  • 如果 hashmap 包含最大值,则应打印其对应的键。哈希表和地图非常新。帮助将不胜感激。谢谢
  • 是打印所有的键而不是你想要的吗?
  • 是的,它正在打印所有的键。

标签: java hashmap hashtable


【解决方案1】:

首先,这些值可能出现多次次 - 我假设您想打印 所有 个匹配键?

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

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

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

【讨论】:

  • 嗨,是的。我正在尝试打印所有匹配的类型。 Map.entry 如何再次工作?我对 java 和哈希表很陌生。
  • @user872009:Map.Entry 类型是“哈希表中的条目”——单个键/值对。 entrySet() 方法返回一组可以迭代的条目。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-11
  • 2011-10-27
  • 2012-08-10
  • 2014-11-30
  • 1970-01-01
  • 2017-09-30
  • 2013-09-30
相关资源
最近更新 更多