Find duplicate characters in a String

In this article we will explain you that how to find the duplicate character in a String.

For example, if you input to your program “Java”, then it should print all the duplicates characters i.e. characters which appears more than once in a String and its count e.g.ย a = 2, because the characterย ‘a’ย is appeared twice in a Stringย “Java”.

It is very popular coding question in Java interviews and written test.

The usual way to solve this programming problem is to make the character array from String and iterate over that and build a Map with character and its count. Nowย iterate over that Mapย and print the characters which have been appeared more than once.

Now we will useย HashMapย to store characters and its count. We will useย containsKey()ย method to check if key that is a character already exists or not, and if it already exists then we will get the old count fromย HashMapย usingย get()ย method and store it back after incrementing it by 1.

After storing characters and its count in HashMap we will find the unique character in String by converting it to Set. Now we will iterate over Set and print with characters which have count more than one.

Now look at the Java program to find the duplicate characters in String in Java.

import java.util.HashMap;  
import java.util.Map;  
import java.util.Set;  
   
public class FindDuplicatesChar 
{

	//Method which will find duplicates
	public void findDupChar(String str) 
	{
		
		// Creating HashMap which will store character as a key and number of times it occur as value
        Map<Character, Integer> hm = new HashMap<Character, Integer>();  
    
        //converting String to Array of character
        char[] charArray = str.toCharArray();
        
        // looping on array of characters
        for (Character ch : charArray) 
        {  
            if (hm.containsKey(ch))
            {  
                hm.put(ch, hm.get(ch) + 1);  
            } 
            else 
            {  
                hm.put(ch, 1);  
            }  
        }  
        //Converting to Set to find unique characters 
        Set<Character> keys = hm.keySet();  
        for (Character ch : keys)
        {  
            if (hm.get(ch) > 1) 
            {  
                System.out.println(ch + "  is " + hm.get(ch) + " times");  
            }  
        }  
    }  
	
	
	
	
	public static void main(String[] args) {
		
		FindDuplicatesChar fd = new FindDuplicatesChar();  
        fd.findDupChar("JavaTechnology");  
		

	}

}
#Outptu#
a  is 2 times
o  is 2 times

Conclusion

In this program you have learnt about how to find the duplicate characters in String in java using HashMap.

Newsletter Updates

Enter your name and email address below to subscribe to our newsletter

Leave a Reply