java - 查找哈希表中有多少个键具有相同的值?

标签 java hashmap hashtable

在哈希表(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 将具有相同的值。我怎样才能检测到这一点?

最佳答案

首先,您必须在 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

关于java - 查找哈希表中有多少个键具有相同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25777960/

相关文章:

c++ - 什么数据结构通常用于hold to hash table for a hashmap

java - HashMap:它在TextView中显示最小值,但min_variable有更多值

运行时Java Hashmap到对象

java - ConcurrentHashMap 的 concurrencyLevel 参数给我们什么保证?

Java对象和数组内存位置

php - 当这些数组是映射(又名哈希表)时,如何记录 PHPDoc 中的数组类型?

java - Apache Ignite 作为多个数据库或其他持久性的统一外观

java - 模数问题

java - 如果 20% 或第 20 个测试用例测试方法失败,我如何停止 Selenium 自动化?

Java 模式捕获词