Map exercises output the number of times each character appears

Map collection exercises

Given a string, please output which characters the string consists of, and how many times does each character appear?

public static void main(String[] args) {
    
    
		//给定字符串判断字符串中每一个字符的个数
		/**
		 * 1、将字符串转换成字符数组
		 * 2、定义Map集合,String,Integer
		 * 	   循环遍历每一个字符
		 *   判断这个map中是否包含这个key 
		 *   	1、如果不存在这个key,那么就将当前这个字符作为key,value就是1
		 *      2、如果存在这个key,就在value上加1 
		 */
		String str = "321jsdadasgryhrghtyugrgawf";
		
		//1、将字符串转换成字符数组
		char[] ch = str.toCharArray();
		//2、定义Map集合,String,Integer
		Map<Character, Integer> map = new HashMap<Character, Integer>();
		//3、循环遍历每一个字符
		for (int i = 0; i < ch.length; i++) {
    
    
			//4、判断这个map中是否包含这个key 
			if(map.containsKey(ch[i])) {
    
    
				//b、如果存在这个key,就在value上加1 
				int count = map.get(ch[i]);
				map.put(ch[i],count+1);
			}else {
    
    
				//a、如果不存在这个key,那么就将当前这个字符作为key,value就是1
				map.put(ch[i],1);
			}
		}
		System.out.println(map);
	}
 输出结果:
 {a=3, d=2, f=1, g=4, h=2, j=1, 1=1, 2=1, r=3, 3=1, s=2, t=1, u=1, w=1, y=2}

Guess you like

Origin blog.csdn.net/weixin_44906436/article/details/108659912