统计字符串中每个单词的次数并按照从大到小输出java程序实现
时间: 2024-03-12 18:48:35 浏览: 24
可以使用Java中的HashMap来实现统计字符串中每个单词的次数,并使用Collections工具类中的sort方法按照从大到小的顺序输出。
示例代码:
```
import java.util.*;
public class WordCount {
public static void main(String[] args) {
String str = "hello world hello java world";
String[] words = str.split(" ");
Map<String, Integer> wordCount = new HashMap<>();
// 统计每个单词出现的次数
for (String word : words) {
if (wordCount.containsKey(word)) {
int count = wordCount.get(word);
wordCount.put(word, count + 1);
} else {
wordCount.put(word, 1);
}
}
// 将统计结果按照从大到小排序并输出
List<Map.Entry<String, Integer>> list = new ArrayList<>(wordCount.entrySet());
Collections.sort(list, (o1, o2) -> o2.getValue().compareTo(o1.getValue()));
for (Map.Entry<String, Integer> entry : list) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}
```
在上面的示例中,首先使用split方法将字符串按照空格分割成单词数组,然后使用HashMap统计每个单词出现的次数。接着,将HashMap转换为List并使用Collections.sort方法按照从大到小排序,并遍历输出每个单词及其出现次数。