Java Program to Find First non Repeated Character in a String

Java Program to Find First non Repeated Character in a String thumbnail
4K
By Dhiraj Ray 16 February, 2020

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;
        Map charactersMap = 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

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.

Share

If You Appreciate This, You Can Consider:

We are thankful for your never ending support.

About The Author

author-image
A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.