Java Online Compiler
Example: First Non-Repeating Character using Java 8 Stream API in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// First Non-Repeating Character using Java 8 Stream API import java.util.LinkedHashMap; import java.util.Optional; import java.util.function.Function; import java.util.stream.Collectors; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { String input1 = "swiss"; String input2 = "teeter"; String input3 = "aabbcc"; String input4 = "java"; String input5 = ""; System.out.println("Input: \"" + input1 + "\" -> First non-repeating character: " + findFirstNonRepeatingCharStream(input1).orElse(' ')); System.out.println("Input: \"" + input2 + "\" -> First non-repeating character: " + findFirstNonRepeatingCharStream(input2).orElse(' ')); System.out.println("Input: \"" + input3 + "\" -> First non-repeating character: " + findFirstNonRepeatingCharStream(input3).orElse(' ')); System.out.println("Input: \"" + input4 + "\" -> First non-repeating character: " + findFirstNonRepeatingCharStream(input4).orElse(' ')); System.out.println("Input: \"" + input5 + "\" -> First non-repeating character: " + findFirstNonRepeatingCharStream(input5).orElse(' ')); } public static Optional<Character> findFirstNonRepeatingCharStream(String str) { // Step 1: Handle null or empty string if (str == null || str.isEmpty()) { return Optional.empty(); } // Step 2: Stream characters, group them by identity, count occurrences, // and collect into a LinkedHashMap to preserve order. Map<Character, Long> charCounts = str.chars() .mapToObj(c -> (char) c) .collect(Collectors.groupingBy( Function.identity(), LinkedHashMap::new, // This ensures insertion order is preserved Collectors.counting() )); // Step 3: Stream the entries of the charCounts map, filter for count 1, and find the first character return charCounts.entrySet().stream() .filter(entry -> entry.getValue() == 1) .map(Map.Entry::getKey) .findFirst(); } }
Output
Clear
ADVERTISEMENTS