本帖最后由 于星星 于 2012-7-18 22:54 编辑
HashMap是为了存放每个单词和单词出现的次数键值对,而TreeMap则是为了排序。当然这里面也可以直接用TreeMap,代码如下:
package test;
import java.util.*;
import java.util.Map.*;
public class Test {
public static void main(String[] args){
String text = "Having a good day. Have a good class." +
"Having a good visit. Have fun!";
Map<String,Integer> treeMap = new TreeMap<String,Integer>(); //直接使用TreeMap,不用HashMap
String[] words = text.split("[ .!?]");
for(int i=0;i<words.length;++i){
if(words.length()>1){
if(treeMap.get(words) != null){
int value = treeMap.get(words).intValue();
value ++;
treeMap.put(words,value);
}else{
treeMap.put(words,1);
}
}
}
System.out.println("Display words and their count in"+" ascending order of the words1");
System.out.println(treeMap);
}
}
输出结果:
Display words and their count in ascending order of the words1
{Have=2, Having=2, class=1, day=1, fun=1, good=3, visit=1}
使用TreeMap后,你也可以自定义比较器TreeMap(Comparator<? super K> comparator)
实现自定义排序!
|