🎓 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
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
- Prompt for Input: Use the
Scannerclass to read a string input from the user. - Use Java 8 Streams to Count Characters:
- Convert the string into a stream of characters.
- Use a
Collectorto group the characters and count their occurrences.
- 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 anIntStreamof character codes. mapToObj(c -> (char) c)converts these character codes back to characters.- The
collect()method withCollectors.groupingBy()groups the characters and usesCollectors.counting()to count the occurrences of each character.
- The
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.
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