Java 8- Count the occurrences of Character in String


In this Java 8 program, you will find how to  count the frequency of character in String using Stream API.

Suppose you have a string “ABCDFCBBA” and in this occurrences of each character is: A=2, B=3, C=2, D=1, F=1

CountOccurrences.java
package org.websparrow;

import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class CountOccurrences {

    public static void main(String[] args) {

        String str = "ABCDFCBBA";

        Map<Character, Long> frequency1 = str.chars()
                .mapToObj(ch -> (char) ch)
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        System.out.println(frequency1);

        //OR

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

        System.out.println(frequency2);

        //OR

        Map<Character, Long> frequency3 = str.codePoints()
                .mapToObj(ch -> (char) ch)
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        System.out.println(frequency3);
    }
}

Output:

console.log
{A=2, B=3, C=2, D=1, F=1}
{A=2, B=3, C=2, D=1, F=1}
{A=2, B=3, C=2, D=1, F=1}

Related Post: How to count the frequency of a character in a string in Java

References

  1. Java 8 Collectors.groupingBy() Method Example
  2. Interface IntStream – JavaDoc

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.