【问题标题】:Find how many keys have the same value in a hashtable?找出哈希表中有多少个键具有相同的值?
【发布时间】:2014-09-11 02:12:37
【问题描述】:

在一个哈希表(Java)中,我怎样才能找到有多少个键具有相同的值?

说我有:

Hashtable<String, int> table = new Hashtable<String, int>();
table.put("a", 1);
table.put("b", 2);
table.put("c", 2);
table.put("d", 2);

在这种情况下,键:b、c 和 d 将具有相同的值。我怎样才能检测到?

【问题讨论】:

  • 您需要构建一个反向映射,一个以值作为键,以计数器作为值的映射。然后遍历第一个映射的条目,从第二个映射中获取其键与第一个映射条目的值匹配的条目,并增加计数器。

标签: java hashmap hashtable


【解决方案1】:

首先,您必须在Hashtable 定义中使用引用类型(对象)。你不能使用像int 这样的原始类型,你必须使用Integer

就您的问题而言,您可以使用这样的小函数来计算某个值在HashTable 中出现的次数:

int countOccurences(Hashtable<String, Integer> table, int value) {
    int count = 0;
    for(String key : table.keySet()) {
        if(table.get(key) == value) {
            count++;
        }
    }
    return count;
}

所以如果你想知道值 2 在表中出现了多少次:

Hashtable<String, Integer> table = new Hashtable<String, Integer>();
table.put("a", 1);
table.put("b", 2);
table.put("c", 2);
table.put("d", 2);
System.out.println(countOccurences(table, 2));

这将打印 3

【讨论】:

  • 感谢您的简单回答。我对哈希表和地图以及与之相关的所有内容都很陌生,并没有真正理解第一个答案。
  • 不客气 :)。坚持练习,越练越有道理
【解决方案2】:

您不能在 Collection 中拥有原始类型(您需要使用包装类型)。我建议您也使用钻石运算符。我会得到keySet 并迭代键,获取每个值并将其添加到SortedSet (如果Set 还没有包含它,如果它包含我会打印它)。所以,我相信你正在寻找这样的东西,

Hashtable<String, Integer> table = new Hashtable<>();
table.put("a", 1);
table.put("b", 2);
table.put("c", 2);
table.put("d", 2);
Set<String> keySet = table.keySet();
SortedSet<Integer> toCount = new TreeSet<>();
for (String key : keySet) {
    Integer val = table.get(key);
    if (!toCount.contains(val)) {
        System.out.printf("Key %s has value %d%n", key, val);
        toCount.add(val);
    } else {
        System.out.printf("Key %s also has value %d%n", key, val);
    }
}

哪些输出

Key b has value 2
Key a has value 1
Key d also has value 2
Key c also has value 2

【讨论】:

    【解决方案3】:
    Map<Integer, Integer> occurenceForValue = new HashMap<Integer, Integer>();
    Hashtable<String, Integer> table = new Hashtable<String, Integer>();
    Iterator it = table.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pairs = (Map.Entry)it.next();
        if(!occurenceForValue.containsKey(pairs.getValue())
        {
            occurenceForValue.put(pairs.getValue(), 1);
        }
        else
        {
            occurenceForValue.put(pairs.getValue(), occurenceForValue.get(pairs.getValue()) + 1);
        }
    
    
        it.remove(); 
    }
    

    然后,occurrenceForValue 将包含每个值(作为键)的出现次数。

    编辑:请注意,在我的代码中,我更正了您使用 int 作为泛型类型的 HashTable 定义,这是不允许的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-03
      • 2011-10-04
      • 1970-01-01
      • 2015-07-26
      • 2011-06-01
      • 2018-11-13
      相关资源
      最近更新 更多