java哈希表创建字体,Java8:使用字符串的字符数创建HashMap

Wondering is there more simple way than computing the character count of a given string as below?

String word = "AAABBB";

Map 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);

解决方案

Simplest way to count occurrence of each character in a string, with full Unicode support (Java 11+)1:

String word = "AAABBB";

Map 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: For Java 8+ (doesn't support characters from supplemental planes, e.g. emoji):

Map charCount = IntStream.range(0, word.length())

.mapToObj(i -> word.substring(i, i + 1))

.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

UPDATE 2: Also for Java 8+.

I was mistaken, thinking that codePoints() wasn't added until Java 9. It was added in Java 8 to the CharSequence interface, so it doesn't show in javadoc for String in Java 8, and shows as added in Java 9 for later versions of the javadoc.

However, the Character.toString​(int codePoint) method wasn't added until Java 11, so to use the Character.toString​(char c) method, we can use chars() in Java 8:

Map charCount = word.chars().mapToObj(c -> Character.toString((char) c))

.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

Or for full Unicode support, incl. supplemental planes, we can use codePoints() and the String(int[] codePoints, int offset, int count) constructor, in Java 8:

Map charCount = word.codePoints()

.mapToObj(cp -> new String(new int[] { cp }, 0, 1))

.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值