Java Online Compiler
Example: First Non-Repeating Character using LinkedHashMap in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// First Non-Repeating Character using LinkedHashMap import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; // 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: " + findFirstNonRepeatingCharLinkedHashMap(input1).orElse(' ')); System.out.println("Input: \"" + input2 + "\" -> First non-repeating character: " + findFirstNonRepeatingCharLinkedHashMap(input2).orElse(' ')); System.out.println("Input: \"" + input3 + "\" -> First non-repeating character: " + findFirstNonRepeatingCharLinkedHashMap(input3).orElse(' ')); System.out.println("Input: \"" + input4 + "\" -> First non-repeating character: " + findFirstNonRepeatingCharLinkedHashMap(input4).orElse(' ')); System.out.println("Input: \"" + input5 + "\" -> First non-repeating character: " + findFirstNonRepeatingCharLinkedHashMap(input5).orElse(' ')); } public static Optional<Character> findFirstNonRepeatingCharLinkedHashMap(String str) { // Step 1: Handle null or empty string if (str == null || str.isEmpty()) { return Optional.empty(); } // Step 2: Use LinkedHashMap to store character counts and maintain insertion order Map<Character, Integer> charCounts = new LinkedHashMap<>(); for (char c : str.toCharArray()) { charCounts.put(c, charCounts.getOrDefault(c, 0) + 1); } // Step 3: Iterate through the LinkedHashMap to find the first character with a count of 1 for (Map.Entry<Character, Integer> entry : charCounts.entrySet()) { if (entry.getValue() == 1) { return Optional.of(entry.getKey()); } } // Step 4: If no non-repeating character is found return Optional.empty(); } }
Output
Clear
ADVERTISEMENTS