java编写一个程序,对一个字符串中的所有单词进行计数,并按照出现次数从大到小排序输出。
时间: 2024-03-16 18:41:14 浏览: 23
好的,以下是一个基于HashMap实现的Java程序:
```java
import java.util.*;
public class WordCount {
public static void main(String[] args) {
String str = "hello world hello java world java world";
String[] words = str.split("\\s+");
Map<String, Integer> wordCount = new HashMap<>();
// 统计每个单词出现的次数
for (String word : words) {
if (wordCount.containsKey(word)) {
wordCount.put(word, wordCount.get(word) + 1);
} else {
wordCount.put(word, 1);
}
}
// 将单词按照出现次数从大到小排序
List<Map.Entry<String, Integer>> wordList = new ArrayList<>(wordCount.entrySet());
Collections.sort(wordList, (o1, o2) -> o2.getValue().compareTo(o1.getValue()));
// 输出结果
for (Map.Entry<String, Integer> entry : wordList) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}
```
假设输入的字符串为:"hello world hello java world java world",输出结果为:
```
world : 3
hello : 2
java : 2
```