'Java8: Create HashMap with character count of a String

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


Solution 1:[1]

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

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

Solution 2:[2]

     String str = "Hello Manash";
    Map<Character,Long> hm = str.chars().mapToObj(c-> 
    (char)c).collect(Collectors.groupingBy(c->c,Collectors.counting()));
    System.out.println(hm);

Solution 3:[3]

Try the below approaches:

Approach 1:

    String str = "abcaadcbcb";
    
    Map<Character, Integer> charCount = str.chars()
            .boxed()
            .collect(toMap(
                    k -> (char) k.intValue(),
                    v -> 1,         // 1 occurence
                    Integer::sum));
    System.out.println("Char Counts:\n" + charCount);

Approach 2:

    String str = "abcaadcbcb";
    Map<Character, Integer> charCount = new HashMap<>();
    for (char c : str.toCharArray()) {
        charCount.merge(c,          // key = char
                1,                  // value to merge
                Integer::sum);      // counting
    }
    System.out.println("Char Counts:\n" + charCount);

Output:

    Char Counts:
    {a=3, b=3, c=3, d=1}

Solution 4:[4]

String str = "abcaadcbcb";

Map<String, Long> charCount  = 
Arrays.asList(str.split("")).stream().collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
    

Solution 5:[5]

Hope this help : Java 8 Stream & Collector:

    String word = "AAABBB";
    Map<Character, Integer> charCount = word.chars().boxed().collect(Collectors.toMap(
                    k -> Character.valueOf((char) k.intValue()),
                    v -> 1,
                    Integer::sum));
    System.out.println(charCount);

Output:
    {A=3, B=3}

Solution 6:[6]

Figured out, below is another simple way.

Map<String, Integer> charCount = new HashMap();
    for(String charr: s.split("")){
        charCount.put(charr,charCount.getOrDefault(charr,0)+1);
}

Solution 7:[7]

Try this one :

    List<Character> chars=Arrays.asList('h','e','l','l','o','w','o','r','l','d');
    Map<Character,Long> map=chars.stream().map(c->c).
    collect(Collectors.groupingBy(c->c,Collectors.counting()));
    System.out.println(map);

output:

{r=1, d=1, e=1, w=1, h=1, l=3, o=2}

Solution 8:[8]

word.chars().mapToObj(c-> (char)c).collect(Collectors.groupingBy(Function.identity(),LinkedHashMap::new, Collectors.counting()));

This will give you character count in order of appearance of the character.

Solution 9:[9]

String str = "edcba"

Map<String, Long> couterMap1 = str.codePoints()
                                  .mapToObj(Character::toString)
                                  .collect(Collectors.groupingBy(e -> e, Collectors.counting()));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Manash Ranjan Dakua
Solution 3
Solution 4 Lijo
Solution 5
Solution 6 OTUser
Solution 7 ASR
Solution 8
Solution 9 Abra