java:集合框架(统计字符串中每个字符出现的次数)

版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/qq_24644517/article/details/83089791
import java.util.HashMap;

public class Test1 {

	public static void main(String[] args) {
		String s = "aaaabbbcccccccccc";
		char[] arr=s.toCharArray();
		HashMap<Character, Integer> hm=new HashMap<>();
		for (char e : arr) {//遍历字符数组
//			if(!hm.containsKey(c)) {//如果不包含这个键
//				hm.put(c, 1);
//			}else {
//				hm.put(c, hm.get(c)+1);
//			}
			hm.put(e, !hm.containsKey(e)?1:hm.get(e)+1);
		}
		for (Character key : hm.keySet()) {
			System.out.println(key+"="+hm.get(key));
		}
	}

}

猜你喜欢

转载自blog.csdn.net/qq_24644517/article/details/83089791