Simplest way to count occurrence of each character in a string, with full Unicode support (Java 11+)1:
String word = "AAABBB";
Map<String, Long> charCount = word.codePoints().mapToObj(Character::toString)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(charCount);
1) Java 8 version with full Unicode support is at the end of the answer.
Output
{A=3, B=3}
UPDATE:对于 Java 8+(不支持补充平面中的字符,例如表情符号):
Map<String, Long> charCount = IntStream.range(0, word.length())
.mapToObj(i -> word.substring(i, i + 1))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
更新2:也适用于 Java 8+。
我错了,以为codePoints()直到 Java 9 才添加。在 Java 8 中添加到CharSequence接口,因此它不会显示在 javadoc 中String在 Java 8 中,显示为Java 9 中添加对于更高版本的 javadoc。
但是,那Character.toString(int codePoint)方法直到 Java 11 才添加,因此要使用Character.toString(char c)方法,我们可以使用chars()在 Java 8 中:
Map<String, Long> charCount = word.chars().mapToObj(c -> Character.toString((char) c))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
或者获得完整的 Unicode 支持,包括。补充平面,我们可以使用codePoints()和String(int[] codePoints, int offset, int count)构造函数,在 Java 8 中:
Map<String, Long> charCount = word.codePoints()
.mapToObj(cp -> new String(new int[] { cp }, 0, 1))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));