Java 8 Program to Find the Frequency of Each Character in a Given String

1. Introduction

In this blog post, we'll explore a Java 8 solution to find the frequency of each character in a given string. This is a common problem in programming interviews and a good exercise to understand string manipulation and the use of collections in Java. Java 8 introduced several new features, including Stream API, which makes solving this problem more concise and expressive.

2. Program Steps

1. Import necessary classes and packages.

2. Read the input string from the user.

3. Convert the string into a stream of characters.

4. Group the characters using a collector to count the frequency of each character.

5. Display the frequency of each character in the given string.

3. Code Program

import java.util.Scanner;
import java.util.stream.Collectors;

public class CharacterFrequencyJava8 {
    public static void main(String[] args) {
        // Creating a Scanner object for reading input from the console
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a string:");
        String inputString = scanner.nextLine();

        // Closing the scanner
        scanner.close();

        // Converting the input string to a stream and counting the frequency of each character
        inputString.chars() // Convert the String to an IntStream
                .mapToObj(c -> (char) c) // Convert each int in the stream to a char
                .collect(Collectors.groupingBy(c -> c, Collectors.counting())) // Group by character and count them
                .forEach((character, frequency) -> System.out.println(character + ": " + frequency)); // Print each character and its frequency
    }
}

Output:

Enter a string:
JavaGuides
a: 2
s: 1
d: 1
e: 1
u: 1
v: 1
G: 1
i: 1
J: 1

Explanation:

1. The program begins by importing the Scanner class for reading user input and the necessary classes from the java.util.stream package for working with streams and collectors.

2. A Scanner object is created to read a string input from the user.

3. The input string is then converted into an IntStream representing the ASCII values of each character in the string.

4. The stream is mapped to a Stream<Character> using mapToObj, where each integer value (ASCII) is cast to its corresponding character.

5. The collect method is used with Collectors.groupingBy to group the characters based on their identity, and Collectors.counting() is used to count the occurrences of each character.

6. Finally, the frequency of each character is printed to the console using a forEach loop.

7. The Scanner object is closed to prevent resource leaks.

Comments