java -- 集合 - 9 (Map集合练习-计算一个字符串中每个字符出现的次数)

点击查看:java集合(List、Set、Map)博客目录

java – 集合 - 9 (Map集合)- 练习

需求:
  • 计算一个字符串中每个字符出现的次数。
分析:
  • 获取一个字符串对象
  • 创建一个Map集合,键代表字符,值代表次数。
  • 遍历字符串得到每个字符
  • 判断Map中是否有该键
  • 如果没有,第一次出现,存储次数为1;如果有,值++,再次存储。
  • 打印最终结果。
import java.util.*;
public class Main{
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner in = new Scanner(System.in);
    // 输入字符串
    String str = in.nextLine();
    HashMap<Character,Integer> map = new HashMap<>();
    // 遍历字符串,获取每一个字符
    for(char c : str.toCharArray()) {
         if(map.containsKey(c)) {
             Integer value = map.get(c);
             value++;
             map.put(c, value);
         }else {
             // 字符不在hashMap中
             map.put(c,1);
         }
     }
       //  遍历Map集合
     for(Character key : map.keySet()) {
         Integer value = map.get(key);
 	 System.out.println(key+"="+value);
     }
  }
}
输入+输出:
abcaaabbcddcca
a=5
b=3
c=4
d=2
发布了55 篇原创文章 · 获赞 9 · 访问量 4846

猜你喜欢

转载自blog.csdn.net/weixin_44107920/article/details/104116958