import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Groups {
static public final String POEM=
"Twas brilling,and the slithy toves\n"+
"Did gyre and gimble in the wabe.\n"+
"All mimsy were the borogoves,\n"+
"And the mome raths outgrabe.\n\n"+
"Beware the Jabberwock,my sin,\n"+
"The jaws that bite,the claws that catch.\n"+
"Beware the Jubjub bird,and shun\n"+
"The frumious Bandersnatch.";
public static void main(String[] args){
Matcher m=
// Pattern.compile("(?m)(\\S+)\\s+((\\S+)\\s+(\\S+))$").matcher(POEM);//取后三个单词
// Pattern.compile("\\b[A-Z]\\w+").matcher(POEM);//所有大写单词
// Pattern.compile("\\b\\p{Upper}\\w+").matcher(POEM);//所有大写单词
// Pattern.compile("\\b\\p{Lower}\\w+").matcher(POEM);//所有小写单词
Pattern.compile("\\b[a-z]\\w+").matcher(POEM);//所有小写单词
Map<String,Integer> strMap=new ConcurrentHashMap<String, Integer>();
while(m.find()){
if(strMap.get(m.group())==null)
strMap.put(m.group(), 1);
else
strMap.put(m.group(), strMap.get(m.group())+1);
}
strMap=sortMap(strMap);
for(String danci:strMap.keySet())
System.out.println(danci+"="+strMap.get(danci));
}
public static Map sortMap(Map oldMap) {
ArrayList<Map.Entry<Character, Integer>> list = new ArrayList<Map.Entry<Character, Integer>>(oldMap.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Character, Integer>>() {
public int compare(Entry<java.lang.Character, Integer> arg0,
Entry<java.lang.Character, Integer> arg1) {
return arg1.getValue() - arg0.getValue();
}
});
Map newMap = new LinkedHashMap();
for (int i = 0; i < list.size(); i++) {
newMap.put(list.get(i).getKey(), list.get(i).getValue());
}
return newMap;
}
}
运行结果:
the=7
and=3
that=2
slithy=1
bite=1
in=1
frumious=1
catch=1
mome=1
sin=1
mimsy=1
my=1
bird=1
toves=1
shun=1
raths=1
jaws=1
wabe=1
brilling=1
were=1
outgrabe=1
gimble=1
borogoves=1
gyre=1
claws=1