统计一个字符串中每个字符出现的次数,并按自然顺序输出

时间:2022-12-16 10:59:17
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());
		}		
	}
}