s-day04-Map练习统计字符出现的次数

This commit is contained in:
2026-08-03 10:51:47 +08:00
parent 2f556476e2
commit 375c9ab275
@@ -0,0 +1,57 @@
package com.inmind.map01;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
/*
7.Map练习统计字符串中字符出现的次数
“aabbbcc”---->a:2,b:3,c:2
实现分析:
1.使用scanner接收输入字符串
2.字符串转字符数组
3.创建一个键为字符,值为整数的双列集合
4.遍历字符数组
判断双列集合中是否拥有某个字符为key,如果没有,直接添加,次数设置为1
判断双列集合中是否拥有某个字符为key,如果有,直接修改,次数设置为当前次数+1
5.遍历双列集合
*/
public class MapTest06 {
public static void main(String[] args) {
//1.使用scanner接收输入字符串
Scanner sc = new Scanner(System.in);
System.out.println("请输入字符串:");
String s = sc.nextLine();
//2.字符串转字符数组
char[] chars = s.toCharArray();
//3.创建一个键为字符,值为整数的双列集合
HashMap<Character, Integer> maps = new HashMap<>();
//4.遍历字符数组
for (char key : chars) {
if (maps.containsKey(key)) {
//判断双列集合中是否拥有某个字符为key,如果有,直接修改,次数设置为当前次数+1
/*Integer count = maps.get(key);
maps.put(key, count + 1);*/
maps.put(key, maps.get(key) + 1);
} else {
//判断双列集合中是否拥有某个字符为key,如果没有,直接添加,次数设置为1
maps.put(key, 1);
}
}
//5.遍历双列集合
//键找值
Set<Character> keys = maps.keySet();
for (Character key : keys) {
System.out.println(key+":"+maps.get(key));
}
//键值对遍历
System.out.println("---------------------");
Set<Map.Entry<Character, Integer>> entries = maps.entrySet();
for (Map.Entry<Character, Integer> entry : entries) {
System.out.println(entry.getKey()+":"+entry.getValue());
}
}
}