Find the First Non-Repeating Character in a String

Problem:
Using Java 8 Streams, how do you find the first non-repeating character in a given string?

✅ Example:

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class FirstNonRepeatingCharacter {

    public static void main(String[] args) {
        String input = "Shubham";

        input.chars()
                .mapToObj(ch -> (char) ch)
                .collect(Collectors.groupingBy(
                        ch -> ch,
                        LinkedHashMap::new,  // Maintain insertion order
                        Collectors.counting()))
                .entrySet()
                .stream()
                .filter(entry -> entry.getValue() == 1)  // Filter non-repeating characters
                .map(Map.Entry::getKey)
                .findFirst()
                .ifPresent(System.out::println);
    }
}

✅ Output:

S

✅ Explanation:

  1. Step 1 – Convert String to Stream of Characters: input.chars().mapToObj(ch -> (char) ch)
    • Converts the string "Shubham" into a stream of characters:
      ['S', 'h', 'u', 'b', 'h', 'a', 'm'].
  2. Step 2 – Group by Character Count: .collect(Collectors.groupingBy( ch -> ch, LinkedHashMap::new, Collectors.counting()))
    • Groups characters into a LinkedHashMap<Character, Long>, maintaining insertion order, and counting occurrences.
  3. Step 3 – Filter Non-Repeating Characters: .filter(entry -> entry.getValue() == 1)
    • Keeps only characters that appear exactly once.
  4. Step 4 – Get First Non-Repeating Character: .findFirst()
    • Returns the first non-repeating character (if present).
  5. Step 5 – Print Result: ifPresent(System.out::println);

Java developer with 9+ years of IT experience, sharing tutorials and tips to help learners master Java programming.

Leave a Reply

Your email address will not be published. Required fields are marked *