2013-12-20 49 views

回答

1

這將做訣竅,這是一個有點長,但也許有一些utils包,做同樣的(還沒有找到一個至今):

String[] words = {"this", "is", "is", "repeating"}; 

    TreeMap<Integer, List<String>> frequencyMap = new TreeMap<Integer, List<String>>(); 
    for (String word : words) { 
     Integer frequency = 0; 
     for (String word2 : words) { 
      if (word.equals(word2)) { 
       frequency++; 
      } 
     } 

     if (frequencyMap.containsKey(frequency)) { 
      List<String> wordsWithFrequency = frequencyMap.get(frequency); 
      wordsWithFrequency.add(word); 
     } else { 
      List<String> wordsWithFrequency = new ArrayList<String>(); 
      wordsWithFrequency.add(word); 
      frequencyMap.put(frequency, wordsWithFrequency); 
     } 
    } 

    if (frequencyMap.size() > 0) { 
     List<String> leastFrequentWords = frequencyMap.get(frequencyMap.firstKey()); 
     for (String string : leastFrequentWords) { 
      System.out.println(string + " = " + frequencyMap.firstKey()); 
     } 
    } 

此打印出:

this = 1 
repeating = 1 
+0

嘿感謝的人。有用! –

相關問題