统计每个字符出现的次数相关问题
方法一:map的put方法+遍历
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();
Map 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, map.get(ch) + 1);
long e = System.currentTimeMillis();
System.out.println((e-s)+"ms");
方法二:用数组
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(26)));
String str = sb.toString();
long s = System.currentTimeMillis();
for(int i =0; i
long e = System.currentTimeMillis();
System.out.println((e-s)+"ms");
方法三:map的getOrDefault方法
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.";
Map countMap = new HashMap<>();
for (char c : str.toCharArray()) {
if (Character.isLetter(c)) {
char lowercase = Character.toLowerCase(c);
countMap.put(lowercase, countMap.getOrDefault(lowercase, 0) + 1);
for (char c : countMap.keySet()) {
int count = countMap.get(c);
System.out.println(c + ": " + count);