Find the First Repeating Character in a String in Java

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

✅ Example:

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

public class FindFirstRepeatingCharacter {

    public static void main(String[] args) {
        String input = "repeating-characters";

        input.chars()
                .mapToObj(ch -> (char) ch)
                .collect(Collectors.groupingBy(
                        ch -> ch,
                        LinkedHashMap::new,  // Preserve insertion order
                        Collectors.counting()))
                .entrySet()
                .stream()
                .filter(entry -> entry.getValue() > 1)  // Find characters appearing more than once
                .map(Map.Entry::getKey)
                .findFirst()
                .ifPresent(System.out::println);
    }
}

✅ Output:

e

✅ Explanation:

  1. Step 1 – Convert String to Character Stream: input.chars().mapToObj(ch -> (char) ch)
    • Converts the string "repeating-characters" to a stream of characters.
  2. Step 2 – Group by Character Count: .collect(Collectors.groupingBy( ch -> ch, LinkedHashMap::new, Collectors.counting()))
    • Creates a LinkedHashMap<Character, Long> where the key is the character and the value is the count of occurrences.
    • LinkedHashMap preserves the order of first appearance.
  3. Step 3 – Filter Repeating Characters: .filter(entry -> entry.getValue() > 1)
    • Keeps only characters that occur more than once.
  4. Step 4 – Pick First Repeating Character: .findFirst()
    • Finds the first character (in the original order) that repeats.
  5. Step 5 – Print the Character: 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 *