2017-08-12 15 views
0

我正在用Java編寫一個詞語云計算程序,目前我一直在計數單詞。我不允許使用像kennykumo或opencloud這樣的庫,這些庫對我來說是最重要的。計算地圖中的單詞數:最大的數字不會遞增

用戶輸入文字牆,我已經取出了停用詞並將結果放在ArrayList。然後,我在搜索有效的事件,每次找到重複的單詞時,它會將它添加到地圖中,但它包含每一個單獨的計數,並且我需要最高的計數。這是找到每個單詞最高的循環嗎?

一旦我能夠獲得對單詞的出現次數,我可以繼續爲它分配最大的字體,然後分配給下一個最大的字體,然後顯示給用戶看。

這裏是一些解決方案的圖片代碼,我試過註釋掉了。

ArrayList<String> wordsList = new ArrayList<>(); 
for (String word : arList) { 
    if (!stopWordList.contains(word)) { 
     wordsList.add(word); 
     int occurrences = Collections.frequency(wordsList, word); 

     //System.out.println(word +" "+ occurrences); 

     Map<Integer, String> map = new TreeMap<Integer, String>(); 
     //HashMap<Integer, String> map = new HashMap<>(); 
     map.put(occurrences, word); 

     //Map<String, Long> counts = wordsList.stream().collect(Collectors.groupingBy(e -> e, Collectors.counting())); 
     System.out.println(map); 
     //map.forEach((k,v)->System.out.println("Count : " + k + " word : " + v)); 
     Map<Integer, String> map2 = new TreeMap(Collections.reverseOrder()); 
     map2.putAll(map); 
    } 
} 

感謝您的任何幫助。

回答

0

一些在當前執行中發現的問題:

  1. 這不是因爲重新計算使用Collections.frequency()方法調用每一個字有效。
  2. 這是不正確的:增量機制。

請考慮以下草案執行(見在線評論)找到並瞭解你可以如何糾正和改善你的最初實現(與停用詞等):

import java.util.AbstractMap; 
import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.Collections; 
import java.util.Comparator; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 

public class Program { 
    public static void main(final String[] args) { 
     // Input. 
     final List<String> words = Arrays.asList(
      "Hello", 
      "World", 
      "World", 
      "World", 
      "Goodbye" 
     ); 

     // Output. 
     // Associative container: maps a word to its count. 
     final HashMap<String, Integer> wordToCountMap = new HashMap<>(); 
     for (final String word : words) { 
      // Lookup into the map for the existing word counter. 
      // If the word counter has not been found (we have just met the word for the first time), 
      // create a counter with initial value. 
      Integer wordCounter = wordToCountMap.getOrDefault(word, 0); 

      // In any case, increase the counter and update the map with it. 
      ++wordCounter; 
      wordToCountMap.put(word, wordCounter); 
     } 

     // Output. 
     // Preparing the output. 
     final ArrayList<Map.Entry<String, Integer>> highToLowCountEntries = 
      new ArrayList<>(wordToCountMap.entrySet()); 
     // Sorting the collected entries by word count. 
     Collections.sort(
      highToLowCountEntries, 
      Comparator 
       .comparing(AbstractMap.Entry<String, Integer>::getValue) 
       .reversed() 
     ); 

     System.out.printf("Entries: from high to low count: %s.%n", highToLowCountEntries); 
    } 
} 

希望這有助於。

+0

謝謝!我在其中實現了停用詞循環,並且它完美地工作。 –

+0

@JakeFishlock,我的榮幸!很高興它幫助你! –