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

Introduction

In Java, we can calculate the frequency of each character in a given string by counting how many times each character appears. Java 8 provides functional programming features like Stream, Collectors, and Map that can simplify this task. This guide will walk you through writing a Java 8 program to find the frequency of each character in a string.

Problem Statement

Create a Java program that:

  • Takes a string input.
  • Calculates the frequency of each character.
  • Displays the frequency of each character.

Example:

  • Input: "hello"

  • Output:

    • 'h' -> 1
    • 'e' -> 1
    • 'l' -> 2
    • 'o' -> 1
  • Input: "java"

  • Output:

    • 'j' -> 1
    • 'a' -> 2
    • 'v' -> 1

Solution Steps

  1. Read the String Input: Read the input string from the user or as part of a method.
  2. Convert the String to a Stream: Use the chars() method to convert the string into a stream of characters.
  3. Group Characters by Frequency: Use the Collectors.groupingBy() method to group characters by their frequency and count them.
  4. Display the Result: Print the character frequencies.

Java 8 Program

// Java 8 Program to Find the Frequency of Each Character in a Given String
// Author: https://www.rameshfadatare.com/

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

public class CharacterFrequency {
    public static void main(String[] args) {
        String input = "hello world";

        // Step 1: Convert the string to a stream of characters
        Map<Character, Long> characterFrequency = input.chars()
                .filter(c -> c != ' ') // Optional: Ignore spaces
                .mapToObj(c -> (char) c)
                // Step 2: Group by character and count the frequency
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        // Step 3: Display the frequency of each character
        characterFrequency.forEach((character, frequency) ->
                System.out.println("'" + character + "' -> " + frequency));
    }
}

Explanation

Step 1: Convert the String to a Stream of Characters

  • The chars() method is used to convert the input string into a stream of int values representing the Unicode code points of each character.
  • The filter() method is used to ignore spaces (optional).
  • The mapToObj() method converts the int values back to char objects.

Step 2: Group by Character and Count the Frequency

  • The Collectors.groupingBy() method groups the characters based on their identity using Function.identity().
  • The Collectors.counting() method counts the occurrences of each character in the stream.

Step 3: Display the Frequency of Each Character

  • The forEach() method is used to print each character and its corresponding frequency.

Output Example

'h' -> 1
'e' -> 1
'l' -> 3
'o' -> 2
'w' -> 1
'r' -> 1
'd' -> 1

Example with Different Input

If you modify the input string to:

String input = "java programming";

The output will be:

'j' -> 1
'a' -> 3
'v' -> 1
'p' -> 1
'r' -> 2
'o' -> 1
'g' -> 2
'm' -> 2
'n' -> 1

Conclusion

This Java 8 program demonstrates how to find the frequency of each character in a string using Stream, Collectors, and Map APIs. By leveraging functional programming features, the code becomes more concise and readable. This exercise is valuable for understanding how to manipulate streams and work with advanced features of Java 8 in string operations.

Comments