使用 Java 查找字符串中出现次数最多的字符以及出现的次数?
import java.util.HashMap;
import java.util.Map;
public class TestStringSum {
public static void main(String[] args) {
String str = "abcdefgaaabbb";
int max = 0;
Map<Character, Integer> map = new HashMap<Character, Integer>(str.length());
for (char c : str.toCharArray()) {
Integer i = map.get(c);
int value = (i == null) ? 0 : i;
map.put(c, ++value);
max = value > max ? value : max;
}
for (Character key : map.keySet()) {
if (map.get(key) == max) {
System.out.println("most frequent Character => " + key + ", Count => " + max);
}
}
}
}
点击查看结果
```
most frequent Character => a, Count => 4
most frequent Character => b, Count => 4
```
参考链接