package com.exercise; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; //计算字符串中出现的字符个数 public class TreeMapDemo { public static void main(String[] args) { String str="aabbbccdejtljlssd"; Map map=countChar(str); show(map); } public static Map countChar(String str){ char[] buf=str.toCharArray(); Map<Character, Integer> map=new TreeMap<Character, Integer>(); for(Character c:buf){ if(map.containsKey(c)){ map.put(c, map.get(c)+1); }else{ map.put(c, 1); } } return map; } public static void show(Map map){ //遍历 Set entrySet=map.entrySet(); Iterator<Entry> ite=entrySet.iterator(); while(ite.hasNext()){ Entry entry=ite.next(); System.out.println("Key:"+entry.getKey()+" Value:"+entry.getValue()); } } }