2013-05-06 57 views
2

我有一個方法,需要一個單詞列表。這些單詞是針對以字符串作爲關鍵字,整數作爲值的單詞的hASHmap進行檢查的。字符串是一個單詞,整數表示文本文件中的單詞頻率。如何獲取重複?

目前,單詞列表按照頻率排列,並將它們放入Treemap中,頻率成爲關鍵。

但是,由於不可能有重複鍵,因此Hashmap中具有相同頻率值的任何單詞都不會輸入到Treemap中。

我能做些什麼才能使日期結構包含按其頻率排列的單詞(包括重複單詞)?

//given a list of words return a TreeMap of those words ranked by most frequent occurence 
private TreeMap rankWords(LinkedList unrankedWords) { 

    //treemap to automatically sort words by there frequency, making the frequency count the key. 
    TreeMap<Integer, String> rankedWordsMap = new TreeMap<Integer, String>(); 

    //for each of the words unranked, find that word in the freqMap and add to rankedWords 
    for (int i = 0; i < unrankedWords.size(); i++) { 

     if (freqMap.containsKey((String) unrankedWords.get(i))) { 

      rankedWordsMap.put(freqMap.get((String) unrankedWords.get(i)), 
        (String) unrankedWords.get(i)); 

     } 

    } 

    return rankedWordsMap; 

} 
+0

有**兩個''for-loops'並且如果找到了副本,則將其刪除。 – Tdorno 2013-05-06 17:35:22

+0

@Tdorno但我想要包含具有重複頻率的詞 – user1835504 2013-05-06 17:36:46

+0

使用'TreeMap <整數,列表>'。 – Howard 2013-05-06 17:39:00

回答

4

您應該重新考慮您的數據結構以獲得唯一的密鑰。這聽起來像你的結構是倒置的:它應該是一個Map的單詞來計數,而不是反過來,因爲單詞是唯一鍵,計數是與鍵相關聯的值數據。

+0

我如何按計數排序,還包括重複項? – user1835504 2013-05-06 17:42:52

+0

@ user1835504不使用地圖,而是使用列表。 – 2013-05-06 17:46:30

3

我會從字符串映射到整數頻率開始。

將entrySet()複製到List並按頻率排序。

1

您的過程有點不合適。 TreeMap的合約要求compareTo(...)調用的行爲在TreeMap的生命期間不會改變。換句話說,你不能更新改變排序順序的因素(如改變頻率)。

我的建議是做兩件事情之一:

  • 使用兩個階段,一個計算詞頻(由字鍵),第二階段在他們的頻率進行排序的話
  • 創建自定義數據結構(可能是兩個數組),爲您管理動態特性。

如果性能不重要,我可能會選擇第一個。否則,第二個選項看起來像一個不錯的挑戰

1

製作條目列表並按條目值對它們排序。

List<Map.Entry<String, Integer>> results = new ArrayList<>(); 
results.addAll(freqMap.entrySet()); 
Collections.sort(new Comparator<Map.Entry<String, Integer>() { 
    @Override 
    public int compare(Map.Entry<String, Integer> lhs, 
      Map.Entry<String, Integer> rhs) { 
     int cmp = lhs.getValue() - rhs.getValue(); 
     if (cmp == 0) { 
      cmp = lhs.getKey().compareTo(rhs.getKey()); 
     } 
     return cmp; 
    } 
}); 
+0

+1列表可以有重複項,所以您只需要按值排序。 – 2013-05-06 17:45:54

0

不知道這將是最完美的解決方案,但一旦你的頻率地圖完成後,你可以把每個地圖進入表示每個映射項對象:

class Entry { 
    String word; 
    int frequency; 
} 

然後你只會爲該對象的頻率/值編寫一個比較器來進行排序。

0

你可以使用一個Set的價值爲您TreeMap的,所以你可以做以下的頻率單詞添加到您的地圖

TreeMap<Integer, Set<String>> rankedWordsMap = new TreeMap<>(); 

// inside loop 
String word = (String) unrankedWords.get(i); 
int frequency = freqMap.get(word); 
// get the set of words with the same frequency 
Set<String> wordSet = rankedWordsMap.get(frequency); 
// if not yet existen, create and put it into the map 
if(wordSet == null) { 
    wordSet = new HashSet<>(); 
    rankedWordsMap.put(frequency, wordSet); 
} 
// add the word to set of words 
wordSet.add(word); 

這種方式,你會保持同頻率的所有單詞。