Writing a Java program to find first non-repeated character in a String is a common programming interview question. For example, the first non-repeated character in the String 'devglan for developers' is 'g'.
This program can be used to test some advanced programming skills on usage of Collection framework in Java. The solution of this program can be built with a plain for-each loop by traversing each character of the String but we will be using in-built data structure called as LinkedHashMap and Java 8 stream operations to provide solution to this question.
LinkedHashMap is a Hash table and linked list implementation of the Map interface, with predictable iteration order meaning it maintains unique key and also the insertion order.
Below is the program implementation:
package com.devglan; import java.util.LinkedHashMap; import java.util.Map; public class NonRepeatedCharacter { public static Character findNonRepeatedCharacters(String input){ Character result = null; MapcharactersMap = new LinkedHashMap<>(); input.chars().mapToObj(i -> (char) i).forEach(character -> { if (!charactersMap.containsKey(character)) { charactersMap.put(character, 1); } else { charactersMap.put(character, charactersMap.get(character) + 1); } }); Map.Entry filteredEntry = charactersMap.entrySet().stream().filter(entry -> entry.getValue() == 1).findFirst().orElse(null); if(filteredEntry != null){ result = filteredEntry.getKey(); } return result; } public static void main(String [] args){ String input = "devglan for developers"; Character nonRepeatedChar = findNonRepeatedCharacters(input); if(nonRepeatedChar != null) { System.out.println(String.format("First non repeated character for String %s is : %s", input, findNonRepeatedCharacters(input))); }else { System.out.println("No repeated characters found."); } } }
Output : First non repeated character for String devglan for developers is : g