Java 8 – Find the First Non-Repeated Character in a String

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

🎓 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 (176K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

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

  1. Input String: Define a string that needs to be processed.
  2. Create a Frequency Map: Use Collectors.groupingBy() to create a map of characters and their frequencies.
  3. Find the First Non-Repeated Character: Stream through the string and find the first character that has a frequency of 1.
  4. 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 of int values representing characters.
  • mapToObj(c -> (char) c) converts these int values to characters.
  • Collectors.groupingBy() groups the characters and counts how many times each appears. We use LinkedHashMap 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

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare