当前位置:   article > 正文

使用Map集合统计一个字符串中每个字符出现的个数_用map集合统计字符串中各个字符的数量

用map集合统计字符串中各个字符的数量

一. 题目描述
使用Map集合统计一个字符串中每个字符出现的个数,将结果使用HashMap.entrySet()方法存入set集合,并使用迭代器和foreach方法分别遍历set集合。
二. 流程设计
1.输入字符串
2.转化字符数组,遍历字符数组
3.使用map集合中的方法判断获取到的字符是否在Map对象中,若不存在,value赋值为1,存在,value++
4.将map集合遍历输出结果
三. 代码实现

import java.util.*;
public class Main {
    /**
     * 1.输入字符串
     * 2.转化字符数组,遍历字符数组
     * 3.使用map集合中的方法判断获取到的字符是否在Map对象中,若不存在,value赋值为1,存在,value++
     * 4.将map集合遍历输出结果
     */
    public static <HashMapMap> void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str1 = scanner.next();
        char[] chars = str1.toCharArray();

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

        for (int i = 0; i < chars.length; i++) {
            if (hashMap.containsKey(chars[i])) { //存在key,修改value的值
                Integer value = hashMap.get(chars[i]);
                value++;
                hashMap.put(chars[i], value);
            } else {
                hashMap.put(chars[i], 1); // 不存在key,添加进去
            }

        }

        //遍历hashMap集合
        //1.使用entry键值对方式
        Set<Map.Entry<Character, Integer>> set = hashMap.entrySet();
        //2.使用迭代器遍历Set集合
        Iterator<Map.Entry<Character, Integer>> it = set.iterator();
        while (it.hasNext()) {
            Map.Entry<Character, Integer> next = it.next();
            System.out.println(next.getKey() + "的个数为" + next.getValue());
        }

        //3.使用增强for循环遍历set集合
        System.out.println("使用foreach循环遍历");
        for (Map.Entry<Character, Integer> entry : set) {
            System.out.println(entry.getKey() + "的个数为" + entry.getValue());

        }

    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45

四. 运行截图
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/67245
推荐阅读
相关标签
  

闽ICP备14008679号