Introduction
In this guide, we will learn how to find the first non-repeated character in a given string using Java 8 features. This problem is common in many text-processing tasks and can be efficiently solved with the help of Java Streams.
Problem Statement
Write a Java program that:
- Takes a string as input.
- Finds the first character that does not repeat anywhere in the string.
- Displays the non-repeated character or returns a message if all characters are repeated.
Example:
- Input:
"swiss"
- Output:
'w'
(since 'w' is the first non-repeated character)
Solution Steps
- Input String: Define a string that needs to be processed.
- Create a Frequency Map: Use
Collectors.groupingBy()
to create a map of characters and their frequencies. - Find the First Non-Repeated Character: Stream through the string and find the first character that has a frequency of 1.
- Display the Result: Print the first non-repeated character or display a message if no non-repeated character exists.
Java Program
import java.util.*;
import java.util.stream.Collectors;
public class FirstNonRepeatedCharacter {
public static void main(String[] args) {
// Step 1: Define the input string
String input = "swiss";
// Step 2: Create a frequency map of characters
Map<Character, Long> characterCountMap = input.chars()
.mapToObj(c -> (char) c) // Convert int stream to character stream
.collect(Collectors.groupingBy(c -> c, LinkedHashMap::new, Collectors.counting())); // Use LinkedHashMap to maintain order
// Step 3: Find the first character with a count of 1
Optional<Character> firstNonRepeatedChar = characterCountMap.entrySet()
.stream()
.filter(entry -> entry.getValue() == 1)
.map(Map.Entry::getKey)
.findFirst();
// Step 4: Display the result
if (firstNonRepeatedChar.isPresent()) {
System.out.println("First non-repeated character: " + firstNonRepeatedChar.get());
} else {
System.out.println("No non-repeated character found.");
}
}
}
Output
First non-repeated character: w
Explanation
Step 1: Define the Input String
We start by defining the string:
String input = "swiss";
This is the string where we will look for the first non-repeated character.
Step 2: Create a Frequency Map
We use Java Streams to create a map where each character is a key and its frequency in the string is the value:
input.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(c -> c, LinkedHashMap::new, Collectors.counting()));
input.chars()
converts the string into a stream ofint
values representing characters.mapToObj(c -> (char) c)
converts theseint
values to characters.Collectors.groupingBy()
groups the characters and counts how many times each appears. We useLinkedHashMap
to maintain the order of insertion.
Step 3: Find the First Non-Repeated Character
We filter the map entries to find the first character with a count of 1
:
characterCountMap.entrySet()
.stream()
.filter(entry -> entry.getValue() == 1)
.map(Map.Entry::getKey)
.findFirst();
This checks each entry and finds the first character that appears only once in the string.
Step 4: Display the Result
We print the first non-repeated character or display a message if no such character is found:
if (firstNonRepeatedChar.isPresent()) {
System.out.println("First non-repeated character: " + firstNonRepeatedChar.get());
} else {
System.out.println("No non-repeated character found.");
}
Output Example
Example 1:
For the input "swiss"
, the output is:
First non-repeated character: w
Example 2:
For the input "aabbcc"
, the output is:
No non-repeated character found.
Conclusion
This Java 8 program demonstrates how to find the first non-repeated character in a string using Streams and a frequency map. The solution is efficient, clear, and uses modern Java features to process the string and find the desired result. This approach can be easily adapted for various text-processing tasks.
Comments
Post a Comment
Leave Comment