🎓 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
Finding the first repeated character in a string is a common problem in text processing. With Java 8, this task can be efficiently handled using streams. This guide will show you how to create a Java program that identifies the first repeated character in a given string.
Problem Statement
Create a Java program that:
- Takes a string as input.
- Finds and returns the first repeated character in the string.
- If no character is repeated, returns an appropriate message.
Example 1:
- Input:
"programming" - Output:
The first repeated character is 'r'
Example 2:
- Input:
"abcdef" - Output:
No repeated characters found.
Solution Steps
- Prompt for Input: Use the
Scannerclass to read a string input from the user. - Use Java 8 Streams to Find Repeated Character:
- Convert the string to a stream of characters.
- Use a
Setto track characters that have been seen. - Find the first character that has already been seen.
- Display the Result: Print the first repeated character or an appropriate message if no character is repeated.
Java Program
Java 8 Program to Find the First Repeated Character in a String
import java.util.HashSet;
import java.util.Optional;
import java.util.Scanner;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Java 8 Program to Find the First Repeated Character in a String
* Author: https://www.javaguides.net/
*/
public class FirstRepeatedCharacter {
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: Find the first repeated character using Java 8 streams
Optional<Character> firstRepeated = findFirstRepeatedCharacter(input);
// Step 3: Display the result
if (firstRepeated.isPresent()) {
System.out.println("The first repeated character is '" + firstRepeated.get() + "'");
} else {
System.out.println("No repeated characters found.");
}
}
// Method to find the first repeated character in a string
public static Optional<Character> findFirstRepeatedCharacter(String input) {
Set<Character> seenCharacters = new HashSet<>();
return input.chars() // Convert the string to an IntStream of character codes
.mapToObj(c -> (char) c) // Convert character codes to characters
.filter(c -> !seenCharacters.add(c)) // Filter characters that are already in the set
.findFirst(); // Return the first repeated character if found
}
}
Explanation
Input: The program prompts the user to enter a string.
Finding the First Repeated Character Using Streams:
- The
chars()method converts the string into anIntStreamof character codes. mapToObj(c -> (char) c)converts these character codes back to characters.- The
filter()method is used to check if the character has already been seen by trying to add it to aSet. If the character is already in theSet,add()will returnfalse, making it a repeated character. findFirst()returns the first repeated character if it exists, wrapped in anOptional.
- The
Output: The program prints the first repeated character or a message indicating that no repeated characters were found.
Output Example
Example 1:
Enter a string: programming
The first repeated character is 'r'
Example 2:
Enter a string: abcdef
No repeated characters found.
Example 3:
Enter a string: javaprogram
The first repeated character is 'a'
Explanation of Edge Cases:
- Example 1: The string contains repeated characters, and the first repeated character is 'r'.
- Example 2: The string contains all unique characters, so no repeated characters are found.
- Example 3: The string contains multiple repeated characters, and the first repeated character is 'a'.
Conclusion
This Java 8 program efficiently finds the first repeated character in a string using streams and a Set to track seen characters. The program handles both cases where a repeated character exists and where all characters are unique. The use of streams makes the solution concise and leverages Java 8's functional programming capabilities.
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