-3
我有具有類似數據的字符串數組列表 {「this」,「is」,is「,」repeating「}用Java編寫模式方法以查找數組中最不經常出現的元素
我需要一個Java代碼,這將使我的元件(一個或多個),其是至少重複
輸出應該是 此= 1 重複= 1
預先感謝
我有具有類似數據的字符串數組列表 {「this」,「is」,is「,」repeating「}用Java編寫模式方法以查找數組中最不經常出現的元素
我需要一個Java代碼,這將使我的元件(一個或多個),其是至少重複
輸出應該是 此= 1 重複= 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
嘿感謝的人。有用! –