Given a string, find the first repeated character using streams.

Count every character while keeping their first-appearance order, then return the first character whose count is more than 1. A second reading of the question, the character whose repeat appears earliest, is solved by tracking seen characters with a Set.

Key Points

import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

public class FirstRepeated {

    static Optional<Character> firstWithRepeat(String input) {
        return input.toLowerCase().chars()
                .filter(c -> c != ' ')
                .mapToObj(c -> (char) c)
                .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()))
                .entrySet().stream()
                .filter(e -> e.getValue() > 1)
                .map(Map.Entry::getKey)
                .findFirst();
    }

    static Optional<Character> firstSeenTwice(String input) {
        Set<Character> seen = new HashSet<>();
        return input.toLowerCase().chars()
                .filter(c -> c != ' ')
                .mapToObj(c -> (char) c)
                .filter(c -> !seen.add(c))
                .findFirst();
    }

    public static void main(String[] args) {
        System.out.println(firstWithRepeat("Java Articles are Awesome").orElse('-'));
        System.out.println(firstWithRepeat("abba").orElse('-') + " / " + firstSeenTwice("abba").orElse('-'));
    }
}

Output

a

a / b

Good to Know

The Set-based version stops as soon as it finds the answer, because findFirst() is short-circuiting, so it can be faster on long strings.

Clarify which meaning of "first repeated" the interviewer wants; showing both with the "abba" example is a strong answer.

Interview Tip

A concise interview answer is

I group the characters with groupingBy into a LinkedHashMap with counting() to keep their order, then return the first one with a count above one. If the interviewer means the character whose second occurrence comes first, I instead filter with !seen.add(c) on a HashSet and take findFirst(); both are O(n).

Last updated: 11 November 2026

Previous question: Given a string, find the first non-repeated character using streams.

Next question: Given a list of integers, sort the values using streams.

More Stream API Coding Questions - Level II interview questions

All Stream API Coding Questions - Level II questions