实现思路
- 首先将英文文本按单词进行拆分。
- 使用
Map<String, Integer>
来存储每个单词及其出现的次数,其中键为单词,值为出现次数。
- 遍历拆分后的单词数组,若
Map
中已存在该单词,则将其对应的值加1;若不存在,则将该单词加入Map
并设值为1。
- 将
Map
中的数据转换为List
,并根据单词出现次数进行排序。
- 最后按从高到低的顺序输出单词及其出现次数。
核心代码片段
import java.util.*;
public class WordCount {
public static void main(String[] args) {
String text = "this is a test this is another test";
String[] words = text.split(" ");
Map<String, Integer> wordCountMap = new HashMap<>();
for (String word : words) {
wordCountMap.put(word, wordCountMap.getOrDefault(word, 0) + 1);
}
List<Map.Entry<String, Integer>> list = new ArrayList<>(wordCountMap.entrySet());
list.sort((o1, o2) -> o2.getValue().compareTo(o1.getValue()));
for (Map.Entry<String, Integer> entry : list) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}