/* 练习:”asdkljflasdjfl“获取字符出现的个数 希望打印结果:a(1)c(2) 通过分析发现,每个字母对应次数,是一种映射关系, 注意当发现有映射关系的时候,就可以选择map集合。map集合专门用来存储映射关系。 */ import java.util.*; class TestMap { public static void main(String[] args) { String s = "ababcd"; char [] ch =s.toCharArray(); HashMap<Character,Integer> hm = new HashMap<Character,Integer>(); int count=0; for(int i=0;i<ch.length;i++) { Integer value = hm.get(ch[i]); if(value != null) { count = value; } count++; hm.put(ch[i],count); count = 0; // 方法2 /*if(value==null) { hm.put(ch[i],1); } else { value++; hm.put(ch[i],value); }*/ } System.out.println(hm); StringBuilder sb =new StringBuilder(); Set<Map.Entry<Character,Integer>> pSet = hm.entrySet(); Iterator<Map.Entry<Character,Integer>> pit = pSet.iterator(); while(pit.hasNext()) { Map.Entry<Character,Integer> pEntry = pit.next(); Character key = pEntry.getKey(); Integer value = pEntry.getValue(); sb.append(key + "(" + value +")"); } System.out.println(sb); } }