代码如下所示:
package test3;
/**
* 去英文单词出现的次数
* @author saicy (博客http://blog.csdn.net/sai739295732/)
*/
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main{
private static Scanner scan;
public static void main(String[] args){
scan = new Scanner(System.in);
String str=scan.nextLine();
Main m = new Main();
m.getValue(str);
}
public void getValue(String str){
//提取出单词
Map<String,Integer> map = getString(str,"[a-zA-Z0-9]+");
//排序
TreeSet<Entry<String, Integer>> set = sortMap(map);
//输出数据
for(Entry<String, Integer> entry:set){
System.out.println(entry.getKey()+" "+entry.getValue());
}
}
private TreeSet<Entry<String, Integer>> sortMap(Map<String, Integer> map) {
TreeSet<Entry<String, Integer>> set = new TreeSet<Entry<String, Integer>>(new Comparator<Entry<String, Integer>>() {
@Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
int count1 = o1.getValue().intValue();
int count2 = o2.getValue().intValue();
//比较次数
if(count1>count2){
return -1;
}else if(count1<count2){
return 1;
}else{
//比较手写字母的大小
int key1 = (int)o1.getKey().charAt(0);
int key2 = (int)o2.getKey().charAt(0);
if(key1>key2){
return 1;
}else if(key1<key2){
return -1;
}else{
return 0;
}
}
}
});
set.addAll(map.entrySet());
return set;
}
private Map<String,Integer> getString(String str, String regx) {
Map<String,Integer> map = new LinkedHashMap<>();
//1.将正在表达式封装成对象Patten 类来实现
Pattern pattern = Pattern.compile(regx);
//2.将字符串和正则表达式相关联
Matcher matcher = pattern.matcher(str);
//3.String 对象中的matches 方法就是通过这个Matcher和pattern来实现的。
//System.out.println(matcher.matches());
//查找符合规则的子串
while(matcher.find()){
//获取 字符串
//将截取的英文单词转为小写
String mapKey = matcher.group().toLowerCase();
Integer count = map.get(mapKey);
//存储英文单词出现的次数
if(count!=null){
map.put(mapKey,count.intValue()+1);
}else{
map.put(mapKey,new Integer(1));
}
}
return map;
}
}
输出结果: