用JAVA编写一个程序,从键盘读入一段英文(多行),找出其中所有的英文单词,统计每个单词出现的次数,并按照单词出现次数由大到小排序后输出。
用正则表达式+java 8 stream api
import java.util.*;
public class WordCount {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Map<String, Integer> wordCount = new HashMap<>();
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] words = line.split("\\s+");
for (String word : words) {
if (word.matches("[a-zA-Z]+")) {
wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
}
}
}
List<Map.Entry<String, Integer>> list = new ArrayList<>(wordCount.entrySet());
Collections.sort(list, (a, b) -> b.getValue() - a.getValue());
for (Map.Entry<String, Integer> entry : list) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
}
不知道你这个问题是否已经解决, 如果还没有解决的话: