2014-09-11 88 views
1

在散列表(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將具有相同的值。我如何檢測?

+0

你需要建立一個反向映射,一個與該值作爲密鑰和計數器的值。然後遍歷第一個映射的條目,從第二個映射中獲取條目,該映射的關鍵字與第一個映射條目的值匹配,然後遞增計數器。 – 2014-09-11 02:18:08

回答

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

+0

感謝您的簡單答案。我真的很陌生,哈希表和地圖,所有與它有關的,並沒有真正理解第一個答案。 – user3680799 2014-09-11 12:14:30

+0

你非常歡迎:)。只要不斷練習,你做得越多,就越有意義 – nem035 2014-09-11 15:17:48

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

然後,對於每個值(作爲關鍵字),occurenceForValue將包含出現次數。

編輯:請注意在我的代碼中,我更正了您的HashTable定義,它使用int作爲不允許的泛型類型。

1

你不能有一個集合(你需要使用包裝類型)的基本類型。我建議你也使用鑽石操作員。我會得到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 
相關問題