public class Test {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("");
Random ran = new Random();
for(int i=0;i<2000000;i++) {
sb.append((char) ('a' + ran.nextInt(27)));
}
String str = sb.toString();
//System.out.println(sb);
//统计一下每个字符出现的次数?出现最多?
Map<Character, Integer> map = new HashMap<>();
long s = System.currentTimeMillis();
for (int i = 0; i < str.length(); i++) {
Character ch = str.charAt(i);
if (Objects.isNull(map.get(ch))) {
map.put(ch, 1);
} else {
map.put(ch, map.get(ch) + 1);
}
}
long e = System.currentTimeMillis();
System.out.println((e-s)+"ms");
// System.out.println(map);
}
}
方法二:用数组
public class Test2 {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder(""); //a-z
Random ran = new Random();
for(int i=0;i<2000000;i++) {
sb.append((char) ('a' + ran.nextInt(26)));
}
String str = sb.toString();
// System.out.println(str);
int[] chs =new int[26]; //chs[0] chs[25] 0-a, 25-z
long s = System.currentTimeMillis();
for(int i =0; i<str.length();i++){
char c = str.charAt(i); //if c is a
chs[c-'a']+=1;
}
long e = System.currentTimeMillis();
System.out.println((e-s)+"ms");
//
// for(int i=0;i<chs.length;i++){
// System.out.print((char)(i+'a')+",");
// System.out.println(chs[i]);
// }
}
}
方法三:map的getOrDefault方法
public class Test3 {
public static void main(String[] args) {
String str = "The so-called 'multifunctional' is not adding many elements, " +
"but subtracting them. Only by leaving blank can ten thousand possibilities be created.";
// 创建HashMap用于存储字母和出现次数
Map<Character, Integer> countMap = new HashMap<>();
// 遍历字符串的每个字符
for (char c : str.toCharArray()) {
// 判断是否为字母
if (Character.isLetter(c)) {
// 将字母转为小写形式
char lowercase = Character.toLowerCase(c);
// 更新字母的出现次数,使用Map的getOrDefault方法来获取该字母已有的计数并加一
countMap.put(lowercase, countMap.getOrDefault(lowercase, 0) + 1);
}
}
// 遍历Map输出每个字母及其出现次数
for (char c : countMap.keySet()) {
int count = countMap.get(c);
System.out.println(c + ": " + count);
}
}
}