Write a Java program to print first non-repeating character in given String

Below program illustrates how to print first non-repeating character in given String using Java:

public class FirstNonRepeatedChar {

	public static void main(String[] args) throws Exception {
		String s = "Aishwarya Roy";
		System.out.println(findFirstNonRepeatedChar(s));

	}
	
	private static char findFirstNonRepeatedChar(String s) throws Exception {
		Map<Character, Integer> map = new LinkedHashMap<>(s.length());
		
		s = s.toLowerCase();
		char[] chars = s.toCharArray();
		for(char c : chars) {
			if(map.containsKey(c)) {
				map.put(c, map.get(c) + 1);
			} else {
				map.put(c, 1);
			}
		}
		
		for(Character chr : map.keySet()) {
			if(map.get(chr) == 1) {
				return chr;
			}
		}
		
		throw new Exception("Didn't find any repeating character.");
	}

}

Author: Mahesh

Technical Lead with 10 plus years of experience in developing web applications using Java/J2EE and web technologies. Strong in design and integration problem solving skills. Ability to learn, unlearn and relearn with strong written and verbal communications.