HashMap——统计字符串中每个字符出现的次数
程序员文章站
2022-04-18 11:49:07
...
package myMapDemo;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
public class HashMapDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字符串");
String line = sc.nextLine();
// HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
TreeMap<Character, Integer> hm = new TreeMap<Character, Integer>();//使用TreeMap自动排序
for (int i = 0; i < line.length(); i++) {
char key = line.charAt(i);
Integer value = hm.get(key);
if (value == null) {
hm.put(key, 1);
}
else {
value++;
hm.put(key, value);
}
}
StringBuilder sb = new StringBuilder();
Set<Character> keySet = hm.keySet();
for (Character key : keySet) {
Integer value = hm.get(key);
sb.append(key).append("(").append(value).append(")");
}
String res = sb.toString();
System.out.println(res);
}
}
结果: