赞
踩
一. 题目描述
使用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()); } } }
四. 运行截图
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。