🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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
- Read the String Input: Read the input string from the user or as part of a method.
- Convert the String to a Stream: Use the
chars()method to convert the string into a stream of characters. - Group Characters by Frequency: Use the
Collectors.groupingBy()method to group characters by their frequency and count them. - 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 ofintvalues representing the Unicode code points of each character. - The
filter()method is used to ignore spaces (optional). - The
mapToObj()method converts theintvalues back tocharobjects.
Step 2: Group by Character and Count the Frequency
- The
Collectors.groupingBy()method groups the characters based on their identity usingFunction.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.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment