Java HashMap class implements the map interface by using a hash table. It inherits AbstractMap class and implements Map interface.
package testjava.javatest;
import java.util.HashMap;
public class FirstNonRepeatedHashMap
{
public static char getFirstNonRepeatedChar(String str)
{
HashMap<Character,Integer> myHashMap = new HashMap<Character, Integer>();
// build table [char -> count]
for (int i = 0; i < str.length(); i++)
{
char c = str.charAt(i);
// If char already exist increment by 1 otherwise set value to 1
if (myHashMap.containsKey(c))
{
myHashMap.put(c, myHashMap.get(c) + 1);
}
else
{
myHashMap.put(c, 1);
}
}
// since HashMap doesn't maintain order, going through string again
for (int i = 0; i < str.length(); i++)
{
char c = str.charAt(i);
// Starting from first letter in string check number of occurrences
// If letter found in Hashmap with count == 1 return letter
if (myHashMap.get(c) == 1)
{
return c;
}
}
return 0;
}
public static void main(String[] args)
{
System.out.println("First non repeated Char: " + getFirstNonRepeatedChar("Programs Buzz Programs"));
System.out.println("First non repeated Char: " + getFirstNonRepeatedChar("Hello World Hey World"));
System.out.println("First non repeated Char: " + getFirstNonRepeatedChar("Hey Hey"));
}
}
Output:
First non repeated Char: B
First non repeated Char: y
First non repeated Char: