gpt4 book ai didi

java - java ArrayList 中最常见的 n 个单词

转载 作者:行者123 更新时间:2023-12-01 06:11:16 26 4
gpt4 key购买 nike

我需要在 ArrayList 中找到最常见的单词(n 个单词,因此如果 n = 5,则为最常见的 5 个单词)。

private ArrayList<String> wordList = new ArrayList<String>();


public ArrayList<String> mostOften(int k)
{
ArrayList<String> lista = new ArrayList<String>();
Set<String> unique = new HashSet<String>(wordList);
for (String key : unique)
System.out.println(key + ": " + Collections.frequency(wordList, key));

return lista;
}

该函数需要返回最常见单词的列表,按频率排序。如果两个单词有相同的频率,我需要按字母顺序对它们进行排序。我已经发布了我尝试过的内容,但这只能找到频率,我不知道如何做其余的事情。有什么帮助吗?

最佳答案

public class WordFrequency {

public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Hello");
list.add("Hello");
list.add("aaaa");
list.add("aaaa");
list.add("World");
list.add("abc");
list.add("abc");
list.add("cba");
list.add("abc");
list.add("World");
list.add("abc");
System.out.println(mostOften(list));
}

public static List<Word> mostOften(List<String> words){
Map<String, Word> wordMap = new HashMap<>();
for (String word : words) {
Word currentWord = wordMap.get(word);
if(currentWord == null)
wordMap.put(word, new Word(word, 1));
else
currentWord.frequency++;
}

List<Word> wordList = new ArrayList<>(wordMap.values());
wordList.sort(new Comparator<Word>() {
@Override
public int compare(Word o1, Word o2) {
if(o1.frequency == o2.frequency)
return o1.word.compareToIgnoreCase(o2.word);

/* sort words with high frequency first */
return Integer.compare(o2.frequency, o1.frequency);
}
});
return wordList;
}


}


public class Word{
String word;
int frequency;

public Word(String word, int total) {
this.word = word;
this.frequency = total;
}

public String toString(){
return "[" + word + ", " + frequency + "]";
}
}

关于java - java ArrayList 中最常见的 n 个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34241695/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com