Find first non repeated character in a string in Java.

Find first non repeated character in a string in Java.


Given a string, find the first non-repeating character in it.

Lets see sample input and output:

Algorithm 


We will use the HashMap to store the character as key and number of times it is repeated as value.

Step1:
Iterate through the String and put it in HashMap, if the character key is already present in Map, increment the count.

Step2:
Iterate the String and check against the HashMap, the first occurrence of any character in a String whose repetition count is 1 is our answer.

Java program to find first non repeated character in a String.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.javabypatel.string;
 
import java.util.HashMap;
import java.util.Map;
 
public class FindFirstNonRepeatingCharacter {
    public static void main(String[] args) {
        String str = "madam";
        System.out.println(getFirstNonRepeatingCharacter(str));
    }
 
    private static char getFirstNonRepeatingCharacter(String str) {
        Map<Character, Integer> countMap = new HashMap<>();
 
        for (int i = 0; i < str.length(); i++) {
            int count = countMap.get(str.charAt(i)) == null ? 1 : countMap.get(str.charAt(i)) + 1;
            countMap.put(str.charAt(i), count);
        }
 
        for (int i = 0; i < str.length(); i++) {
            if (countMap.get(str.charAt(i)) == 1) {
                return str.charAt(i);
            }
        }
        return '\0';
    }
}