Java 8 Program To Count Characters in a String

Introduction

Counting the frequency of each character in a string is a common task in text processing. With Java 8, this can be efficiently achieved using streams and collectors. This guide will show you how to create a Java program that counts the occurrences of each character in a given string.

Problem Statement

Create a Java program that:

  • Takes a string as input.
  • Counts the frequency of each character in the string.
  • Returns and displays the count of each character.

Example 1:

  • Input: "hello"
  • Output: h: 1, e: 1, l: 2, o: 1

Example 2:

  • Input: "Java 8 Streams"
  • Output: J: 1, a: 2, v: 1, 8: 1, S: 1, t: 1, r: 1, e: 2, m: 1, s: 1

Solution Steps

  1. Prompt for Input: Use the Scanner class to read a string input from the user.
  2. Use Java 8 Streams to Count Characters:
    • Convert the string into a stream of characters.
    • Use a Collector to group the characters and count their occurrences.
  3. Display the Result: Print the frequency of each character.

Java Program

Java 8 Program to Count Characters in a String

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

/**
 * Java 8 Program to Count Characters in a String
 * Author: https://www.javaguides.net/
 */
public class CharacterCount {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Step 1: Prompt the user for input
        System.out.print("Enter a string: ");
        String input = scanner.nextLine();

        // Step 2: Count the characters using Java 8 streams
        Map<Character, Long> characterCounts = countCharacters(input);

        // Step 3: Display the result
        characterCounts.forEach((character, count) -> 
            System.out.println(character + ": " + count));
    }

    // Method to count characters in a string
    public static Map<Character, Long> countCharacters(String input) {
        return input.chars()  // Convert the string to an IntStream of character codes
                .mapToObj(c -> (char) c)  // Convert character codes to characters
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));  // Group by character and count
    }
}

Explanation

  • Input: The program prompts the user to enter a string.

  • Counting Characters Using Streams:

    • The chars() method converts the string into an IntStream of character codes.
    • mapToObj(c -> (char) c) converts these character codes back to characters.
    • The collect() method with Collectors.groupingBy() groups the characters and uses Collectors.counting() to count the occurrences of each character.
  • Output: The program prints each character and its corresponding frequency.

Output Example

Example 1:

Enter a string: hello
h: 1
e: 1
l: 2
o: 1

Example 2:

Enter a string: Java 8 Streams
J: 1
a: 2
v: 1
 : 2
8: 1
S: 1
t: 1
r: 1
e: 2
m: 1
s: 1

Explanation of Output:

  • Example 1: The string "hello" contains characters 'h', 'e', 'l', and 'o' with 'l' occurring twice.
  • Example 2: The string "Java 8 Streams" contains various characters, including spaces, with their respective frequencies.

Conclusion

This Java 8 program efficiently counts the occurrences of each character in a string using streams and collectors. The program is concise, leveraging Java 8's functional programming capabilities to achieve the task in a straightforward manner. This approach is useful in scenarios where character frequency analysis is needed, such as in text processing or data analysis.

Comments