无意中看见这样一个程序,中分别使用了HashMap和TreeMap,在这个程序中为什么这么用呢,有什么区别吗?请指教
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> hashMap = new HashMap<String,Integer>();
String[] words = text.split("[ .!?]");
for(int i=0;i<words.length;++i){
if(words[i].length()>1){
if(hashMap.get(words[i]) != null){
int value = hashMap.get(words[i]).intValue();
value ++;
hashMap.put(words[i],value);
}else{
hashMap.put(words[i],1);
}
}
}
Map<String,Integer> treeMap = new TreeMap<String,Integer> ();
treeMap.putAll(hashMap);
System.out.println("Display words and their count in"+" ascending order of the words1");
System.out.println(treeMap);
}
}
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}