Java Streams learning path Level 1 This level ยท 17 of 25
Easy java streams

First repeated character

The 30 second answer

I walk the character stream and keep a seen set; the first character whose add returns false is the answer. It short-circuits early, which is nice. The lambda is stateful, so this is sequential only. In many interviews a plain loop is equally fine and sometimes clearer.

Could you say this in an interview?
Set<Character> seen = new HashSet<>();
Optional<Character> r = s.chars()
    .mapToObj(c -> (char) c)
    .filter(c -> !seen.add(c))
    .findFirst();

Short-circuits at the first repeat (O(k) where k is the position of the first duplicate). Stateful lambda โ†’ sequential only.

[Opinion] A plain loop is equally clear here and many interviewers accept or prefer it.

Sources (2)
  1. java.util.stream package (stateless behaviors)docs.oracle.com
  2. Stream.findFirstdocs.oracle.com
Previous
Next