[英]java counting repeated key value pairs?
我有一個Tuple課,其中有:
private class Tuple {
private int fileno;
private int position;
public Tuple(int fileno, int position) {
this.fileno = fileno;
this.position = position;
}
}
我也有一個哈希表像這樣引用此列表
Map<String, List<Tuple>> index = new HashMap<String, List<Tuple>>();
現在有一種情況,我需要計算一個文件中有多少個單詞:數據如下:
abc 10.txt
abc 10.txt
abc 10.txt
abc 12.txt
abc 12.txt
ghost 15.txt
and so on....
現在如何計算上述次數? 這很容易,但是我已經編碼了很長時間了,而且對於Java還是新的。 我還了解到重復項不能進入哈希圖! 謝謝。
要將數據添加到列表:
List<Tuple> idx = index.get(word);
if (idx == null) {
idx = new LinkedList<Tuple>();
index.put(word, idx);
}
idx.add(new Tuple(fileno, pos));
上面的代碼只是轉儲數據,現在我將與字符串array []中的單詞進行比較。 我最后需要的是這樣的:abc 10.txt計數-3 abc 12.txt計數-2 ghost 15.txt計數-1
我不確定地圖是否可以幫助/我是否需要再次使用列表/編寫函數來執行此操作? 謝謝!
我用簡單的條件語句解決了以上問題! 謝謝@codeguru
/*
consider all cases and update wc as along
Lesson learnt - Map does not handle duplicates
- List does not work
- spend half a day figuring out
*/
if(wordInstance == null && fileNameInstance == null) {
wordInstance = wordOccurence;
fileNameInstance = files.get(t.fileno);
}
if(wordInstance == wordOccurence && fileNameInstance ==files.get(t.fileno)) {
wc++;
}
if(wordInstance == wordOccurence && fileNameInstance !=files.get(t.fileno)) {
wc=0;
fileNameInstance = files.get(t.fileno);
wc++;
}
if(wordInstance != wordOccurence && fileNameInstance ==files.get(t.fileno)) {
wc=0;
wordInstance = wordOccurence;
wc++;
}
我認為您可能會使此過程變得比所需的復雜。 我建議您從計算機后退一步。 首先,您應該以一個簡單的輸入示例為例,並手工計算出輸出應該是什么。 接下來,用您的母語寫幾句話,描述為計算此輸出所采取的步驟。 從那里開始,您需要完善描述,直到可以輕松將其翻譯成Java。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.