Find the first non-repeated character in Java



 Write a Java program that returns the first non-repeated character from a given string.

Java program to find the first non-repeated character

import java.util.LinkedHashMap;
import java.util.Map;

public final class Strings {

    public static char firstNonRepeatedCharacterV1(String str) {

        if (str == null || str.isBlank()) {
            // or throw IllegalArgumentException
            return Character.MIN_VALUE;
        }

        for (int i = 0; i < str.length(); i++) {

            char ch = str.charAt(i);

            int count = 0;
            for (int j = 0; j < str.length(); j++) {
                if (ch == str.charAt(j) && i != j) {
                    count++;
                    break;
                }
            }

            if (count == 0) {
                return ch;
            }
        }

        return Character.MIN_VALUE;
    }

    public static char firstNonRepeatedCharacterV3(String str) {

        if (str == null || str.isBlank()) {
            // or throw IllegalArgumentException
            return Character.MIN_VALUE;
        }

        Map<Character, Integer> chars = new LinkedHashMap<>();

        // or use for(char ch: str.toCharArray()) { ... }
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);

            chars.compute(ch, (k, v) -> (v == null) ? 1 : ++v);
        }

        for (Map.Entry<Character, Integer> entry : chars.entrySet()) {
            if (entry.getValue() == 1) {
                return entry.getKey();
            }
        }

        return Character.MIN_VALUE;
    }
}

Test

public class Main {

	private static final String TEXT = " Java is my fav programming language. I love Java coding";

    public static void main(String[] args) {
    	
    	System.out.println("Loop and break solution:");
        char firstcharV1 = Strings.firstNonRepeatedCharacterV1(TEXT);

        System.out.println("Found character: " + firstcharV1);
        
        System.out.println("LinkedHashMap based solution:");

        char firstcharV3 = Strings.firstNonRepeatedCharacterV3(TEXT);

        System.out.println("Found character: " + firstcharV3);
    }
}

Output:

Loop and break solution:
Found character: s
LinkedHashMap based solution:
Found character: s

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course

Comments