我有字符串的arraylist,有类似这样的数据 { “这个”, “是”,是”, “重复”}
我需要一个java代码,它会给我最少重复的元素
输出应该是 这个= 1 重复= 1
提前致谢
答案 0 :(得分:1)
这样就可以了,这有点长,但也许还有一些类似的工具包可以做同样的事情(到目前为止还没找到):
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