使用TreeMap統計單詞個數,并輸出單詞和書目,單詞按升序排列
TreeMap的特點是無重複元素,且元素的key值既可以按預設的Comparable接口排序也可以按Comparator比較器排序,為TreeMap設計一個比較器,此比較器要實作Comparator接口
//可以擴充到從檔案中或者從控制台輸入單詞,來統計,隻需要加入流就行了
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class CountWords {
public static void main(String[] args) {
// TODO Auto-generated method stub
String text="Hello,Good morning.Have a good day!"+"oh,Thank you.Have a good visit!";
TreeMap<String,Integer> treemap=new TreeMap<String,Integer>();
String[] str=text.split("[,.! ]");
for(int i=;i<str.length;i++){
String key=str[i].toLowerCase();
if(key.length()>){
if(!treemap.containsKey(key)){
treemap.put(key, );//如果map裡面沒有,就放入
}
else{
int value=treemap.get(key).intValue();
value++;
treemap.put(key, value); // 如果有此單詞,值加1
}
}
}
Set<Map.Entry<String, Integer>> set=treemap.entrySet();//傳回treemap裡的條目規則集
for(Map.Entry<String, Integer> e:set){
System.out.println(e.getKey()+"\t"+e.getValue());
}
}
}
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiMxIzMxMTM0EDMxgDM1EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)