Count the Occurrence of Each Character in a String in Java

Problem:
Using Java 8 Streams, how do you count the number of occurrences of each character in a given string (ignoring spaces)?

✅ Example:

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

public class CharacterCount {

    public static void main(String[] args) {
        String input = "Hello Everyone";

        Map<String, Long> charToCount = Arrays.stream(input.replaceAll("\\s+", "").split(""))
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        charToCount.forEach((character, count) ->
                System.out.println("Character: " + character + ", Count: " + count));
    }
}

✅ Example Output:

Character: H, Count: 1  
Character: e, Count: 4  
Character: l, Count: 2  
Character: o, Count: 2  
Character: v, Count: 1  
Character: r, Count: 1  
Character: y, Count: 1  
Character: n, Count: 1  

✅ Explanation:

  1. Normalization Step: input.replaceAll("\\s+", "")
    • Removes all spaces from the input string "Hello Everyone""HelloEveryone".
  2. Splitting into Characters: .split("")
    • Splits the string into individual characters: ["H", "e", "l", "l", "o", "E", "v", "e", "r", "y", "o", "n", "e"].
  3. Stream Processing: Arrays.stream(...)
    • Converts the array of characters into a stream.
  4. Grouping and Counting: .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    • Groups characters by themselves and counts the number of occurrences.
  5. Printing the Result: charToCount.forEach((character, count) -> System.out.println(...));

Java developer with 9+ years of IT experience, sharing tutorials and tips to help learners master Java programming.

Leave a Reply

Your email address will not be published. Required fields are marked *