TreeMap的使用实例:统计字符出现次数

import java.util.Map;
import java.util.Set;
import java.util.TreeMap;


/**
 * TreeMap使用实例
 * 将字符串内字符出现的次数进行统计输出
 * @author franky
 *
 */
public class DemoForCalcStr {


	public static void main(String[] args) {
		String str = "jkasdljglgfgfgfgjhjhhkjasdjkljowoiiuxncv";
		
		printCalcStr(str);
		
//		String str2 = "";
//		printCalcStr(str2);//抛出异常
	}

	private static <K, V> void printCalcStr(String str) {
		//1.判断是否为空字符串,如果为空则抛出空字符串异常
		if(str.isEmpty()){
			throw new NullStringException("字符串不能为空");
		}
		
		//2.将字符串分解为字符数组
		char[] chars = str.toCharArray();
		
		//3.new一个TreeMap,遍历字符数组,字符为key,取出value,判断值是否为null
		//为空则存入初始化value 1,如果不为空则自增1,实现自然排序
		
		Map<Character,Integer> map = new TreeMap<Character,Integer>();
		
		for(Character c:chars){
			Integer i = map.get(c);
			int count = 0;
			if(i!=null){
				count = i;
			}
			++count;
			map.put(c, count);
		}
		//4.利用StringBuilder输出统计的字符串
		Set<Character> set = map.keySet();
		StringBuilder sb = new StringBuilder();
		for (Character character : set) {
			Integer integer = map.get(character);
			sb.append(character+"("+integer+")");
		}
		System.out.println(sb.toString());
	}

}

/**
 * 自定义空字符串异常
 * @author franky
 * 
 */
class NullStringException extends RuntimeException{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public NullStringException() {
		super();
	}

	public NullStringException(String message, Throwable cause,
			boolean enableSuppression, boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
	}

	public NullStringException(String message, Throwable cause) {
		super(message, cause);
	}

	public NullStringException(String message) {
		super(message);
	}

	public NullStringException(Throwable cause) {
		super(cause);
	}
}

你可能感兴趣的:(TreeMap)