Java Program to Find First non Repeated Character in a String
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
Explanation
Click to Suggest Your Own Explanation
As LinkedhashMap maintains unique key as well as inserton order, we will traverse the every character of the String and populate the Map with key as the character of the string and value as it's count. If the Map already contains the key, we will simply increase the count and at the end we will have each character as a key and it's count as value. Since, LinkedhashMap maintains insertion order, we will loop the Map and find the first key whose value is equal to 1. This key will be the first non repeated character in a String.
Other Similar Java Programs:
If You Appreciate This, You Can Consider:
- Share this article on social media or with your teammates.