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:
- 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']
.
- Converts the string
- 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.
- Groups characters into a
- Step 3 – Filter Non-Repeating Characters:
.filter(entry -> entry.getValue() == 1)
- Keeps only characters that appear exactly once.
- Step 4 – Get First Non-Repeating Character:
.findFirst()
- Returns the first non-repeating character (if present).
- Step 5 – Print Result:
ifPresent(System.out::println);