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:
- Step 1 – Convert String to Character Stream:
input.chars().mapToObj(ch -> (char) ch)
- Converts the string
"repeating-characters"
to a stream of characters.
- Converts the string
- 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.
- Creates a
- Step 3 – Filter Repeating Characters:
.filter(entry -> entry.getValue() > 1)
- Keeps only characters that occur more than once.
- Step 4 – Pick First Repeating Character:
.findFirst()
- Finds the first character (in the original order) that repeats.
- Step 5 – Print the Character:
ifPresent(System.out::println);