java 利用map(键不能重复原理 来写一个—— 字符出现次数的小Demo)

public class AugrumentDemo {
    public static void main(String[] args) {


        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();

        HashMap<Character,Integer> hs = new HashMap<Character, Integer>();

        char[] chars = str.toCharArray();
        for (int i = 0; i <chars.length ; i++) {

            //先判断集合中是否包含了这个字符键
            if(hs.containsKey(chars[i])){
                //如果包含这个字符键 获取它的值
                Integer value = hs.get(chars[i]);
                value++;  //在原来的值上++
                hs.put(chars[i],value); //重新存储最新的值
            }else{

                //如果是第一次则直接存储
                hs.put(chars[i],1);
            }
        }


        for(Character c : hs.keySet()){
            System.out.println(c+":"+hs.get(c));
        }
   }
}
坚持
原文地址:https://www.cnblogs.com/gaoSJ/p/12857892.html