代碼如下所示:
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;
}
}
輸出結果: