使用字符串的字符数创建HashMap

使用字符串的字符数创建HashMap

本文介绍了Java8:使用字符串的字符数创建HashMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想知道的是,比计算给定字符串的字符数更简单的方法如下:

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

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


推荐答案

计算字符串中每个字符出现的最简单方法,具有完整的Unicode支持(Java 11 +):

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

String word = "AAABBB";
Map<String, Long> charCount = word.codePoints().mapToObj(Character::toString)
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(charCount);

输出

{A=3, B=3}






更新:对于Java 8+(不支持补充平面中的字符,例如emoji):


UPDATE: For Java 8+ (doesn't support characters from supplemental planes, e.g. emoji):

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 +。


UPDATE 2: Also for Java 8+.

我想错了,以为 Java 8中的接口,因此对于在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.

不过,方法直到Java 11才被添加,因此要使用方法,我们可以使用在Java 8中:

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<String, Long> charCount = word.chars().mapToObj(c -> Character.toString((char) c))
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

或者对于完整的Unicode支持,包括补充平面,我们可以使用和构造函数,在Java 8中:

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<String, Long> charCount = word.codePoints()
        .mapToObj(cp -> new String(new int[] { cp }, 0, 1))
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

这篇关于Java8:使用字符串的字符数创建HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 23:53