簡體   English   中英

從 hashMap 中取出 10 個具有最高值的字符串

[英]Taking 10 Strings with highest values from hashMap

我想將標題中的所有單詞從站點保存到文件中。 然后我想取 10 個最常用的單詞並將它們保存到另一個文件中。 所以我已經保存到文件中。 但我一直在尋找這 10 個詞。 我的代碼只查找 1 個最常用的單詞,僅此而已。 肯定有比我做過的更好的方法來做到這一點。 如果你能給我一些提示,我將不勝感激。 我已經瀏覽了這里最流行的話題,但所有這些話題都是關於尋找一個最常用的詞。

List<String> mostRepeatedWords = new ArrayList<>();
Set<Map.Entry<String, Integer>> entrySet = wordsMap.entrySet();
int max = 0;
for (int i = 0; i < entrySet.size(); i++) {
    for (Map.Entry<String, Integer> entry : entrySet) {   //here I'm looking for the word with the highest value in the map
        if (entry.getValue() > max) {
            max = entry.getValue();
            }
     }
     for (Object o : wordsMap.keySet()) {     //here I write this word to a list
         if (wordsMap.get(o).equals(max)) {
             mostRepeatedWords.add(o.toString());
         }
    }
}

@Edit 這是我數詞的方法:

while (currentLine != null) {
    String[] words = currentLine.toLowerCase().split(" ");

    for (String word : words) {
        if (!wordsMap.containsKey(word) && word.length() > 3) {
            wordsMap.put(word, 1);
        } else if (word.length() > 3) {
            int value = wordsMap.get(word);
            value++;
            wordsMap.replace(word, value);
        }
    }
    currentLine = reader.readLine();
}

這對你有用嗎?

首先,根據出現頻率倒序對map的詞(即keys)進行排序。

List<String> words = mapOfWords.entrySet().stream()
        .sorted(Entry.comparingByValue(Comparator.reverseOrder()))
        .limit(10)
        .map(Entry::getKey)
        .collect(Collectors.toList());

然后使用這些鍵以遞減的頻率打印前 10 個單詞。

for (String word : words) {
    System.out.println(word + " " + mapOfWords.get(word));
}

另一種不使用流的更傳統的方法如下:

測試數據

Map<String, Integer> mapOfWords =
        Map.of("A", 10, "B", 3, "C", 8, "D", 9);

創建地圖條目列表

List<Entry<String, Integer>> mapEntries =
        new ArrayList<>(mapOfWords.entrySet());

定義一個Comparator以根據頻率對條目進行排序

Comparator<Entry<String, Integer>> comp = new Comparator<>() {
    @Override
    public int compare(Entry<String, Integer> e1,
            Entry<String, Integer> e2) {
            Objects.requireNonNull(e1);
            Objects.requireNonNull(e2);
        // notice e2 and e1 order is reversed to sort in descending order.
        return Integer.compare(e2.getValue(), e1.getValue());
    }
};

以上相當於Map.Entry class定義的以下內容

Comparator<Entry<String,Integer>> comp =
   Entry.comparingByValue(Comparator.reverseOrder());

現在使用任一比較器對列表進行排序。

mapEntries.sort(comp);

現在只需打印條目列表。 如果超過 10 個,您將需要放入一個限制計數器或使用mapEntries.subList(0, 10)作為for loop的目標。

for (Entry<?,?> e : mapEntries) {
     System.out.println(e);
}

您可以將最常用的單詞保存到一個數組中,並檢查您找到的下一個單詞是否已存在於該數組中。 然后搜索該數組中不存在的下一個最頻繁的單詞。

假設您已經有了可能如下所示的頻率圖:

Map<String,Integer> wordsMap = Map.of( "foo", 2,
                                       "bar", 7,
                                       "baz", 5,
                                       "doo", 9,
                                       "tot", 2,
                                       "gee", 12);

您可以創建另一張地圖,即前十張地圖(在我的演示中前三名下方),方法是按相反順序按值對地圖進行排序並將其限制為前十個條目

Map<String,Integer> topThree = wordsMap.entrySet()
                                       .stream()
                                       .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
                                       .limit(3)
                                       .collect(Collectors.toMap(
                                          Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,LinkedHashMap::new));

System.out.println(topThree);

//{gee=12, doo=9, bar=7}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM