package com.tedu.study01;
import java.util.*;
public class TestMap {
public static void main(String[] args) {
System.out.println("输入需要统计的字符串:");
String scanner = new Scanner(System.in).next();
// 声明map集合,用于存储每个字符(key)
Map<Character,Integer> m1 = new HashMap<>();
//遍历用户输入的字符串
for (int i = 0; i < scanner.length(); i++) {
// 获取字符串的字符
char ch = scanner.charAt(i);
// 判断当前字符是否在集合中存在
if (m1.containsKey(ch)){
Integer integer = m1.get(ch);
m1.put(ch,++integer);//count++,如果是1,先使用,后==
}else { // 如果不存在就设置当前字符出现的次数为1
m1.put(ch,1);
}
}
Set<Map.Entry<Character,Integer>> entry = m1.entrySet();
Iterator<Map.Entry<Character, Integer>> iterator = entry.iterator();
while (iterator.hasNext()){
Map.Entry<Character, Integer> next = iterator.next();
System.out.println(next.getKey()+":"+next.getValue());
}
}
}
标签:map,ch,java,scanner,iterator,字符,个数,next,m1
From: https://www.cnblogs.com/ch2020/p/16867587.html