Java – Find duplicate characters in String

This article presents a simple Java program to find duplicate characters in a String. This can be a possible Java interview question while interviewer may be evaluating your coding skills.

You can use this code to find repeated characters or modify the code to find non-repeated characters in string.

Find duplicate characters in string

Pseudo steps

  1. Split the string into character array.
  2. Iterate over character array.
  3. For each iteration, use character as map key and check is same character is present in map, already.
  4. If map key does not exist it means the character has been encountered first time. Store it in map with count value to 1.
  5. If map key exist, increment the counter.
  6. Repeat until all characters in array has been iterated.
  7. Check map. Duplicate characters have count more than 1.
  8. Distinct characters will have count as 1.

Java program to find duplicate characters in string

import java.util.HashMap;
import java.util.Map;

public class StringExample 
{
	public static void main(String[] args) 
	{
		String blogName = "howtodoinjava dot com";
		char[] chars = blogName.toCharArray();
		
		Map<Character, Integer> map = new HashMap<>();
		for(char c : chars) 
		{
			if(map.containsKey(c)) {
				int counter = map.get(c);
				map.put(c, ++counter);
			} else {
				map.put(c, 1);
			}
		}
		
		System.out.println("Duplicate characters:");
		
		//Print duplicate characters
		for(char c : map.keySet()) {
			if(map.get(c) > 1) {
				System.out.println(c);
			}
		}
		
		System.out.println("Duplicate characters excluding white space :");
		
		//Print duplicate characters excluding white space
		for(char c : map.keySet()) {
			if(map.get(c) > 1 && !Character.isWhitespace(c)) {
				System.out.println(c);
			}
		}
		
		System.out.println("Distinct characters:");
		
		//Print distinct characters
		for(char c : map.keySet()) {
			if(map.get(c) == 1) {
				System.out.println(c);
			}
		}
	}
}

Program output:

Duplicate characters:
 
a
d
o
t
Duplicate characters excluding white space :
a
d
o
t
Distinct characters:
c
h
i
j
m
n
v
w

We learned how we can use a map to find repeated character in string; also check non-repeated characters as well.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.