Ran*_*aul 2 java string collections hashmap
想知道有没有比如下计算给定字符串的字符数更简单的方法?
String word = "AAABBB";
Map<String, Integer> charCount = new HashMap();
for(String charr: word.split("")){
Integer added = charCount.putIfAbsent(charr, 1);
if(added != null)
charCount.computeIfPresent(charr,(k,v) -> v+1);
}
System.out.println(charCount);
Run Code Online (Sandbox Code Playgroud)
计算字符串中每个字符出现次数的最简单方法,完全支持 Unicode (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);
Run Code Online (Sandbox Code Playgroud)
1) 完全支持 Unicode 的 Java 8 版本在答案的最后。
输出
String word = "AAABBB";
Map<String, Long> charCount = word.codePoints().mapToObj(Character::toString)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(charCount);
Run Code Online (Sandbox Code Playgroud)
更新:对于 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()));
Run Code Online (Sandbox Code Playgroud)
更新 2:也适用于 Java 8+。
我错了,认为codePoints()直到 Java 9 才添加它。它是在 Java 8 中添加到CharSequence界面中的,所以它没有显示String在 Java 8中的 javadoc中,并且显示为在 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()));
Run Code Online (Sandbox Code Playgroud)
或者要获得完整的 Unicode 支持,包括。在 Java 8 中,我们可以使用辅助平面codePoints()和String(int[] codePoints, int offset, int count)构造函数:
Map<String, Long> charCount = word.codePoints()
.mapToObj(cp -> new String(new int[] { cp }, 0, 1))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
Run Code Online (Sandbox Code Playgroud)