Write a Java program to find number of occurrence of duplicate characters in a String using HashMap.

 

package testjava.javatest;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map.Entry;

public class DuplicateCharacterOrNot
{
	public static void main(String args[]) throws NumberFormatException, IOException
	{
		duplicateCharCount("ProgramsBuzz");
		duplicateCharCount("Learn Java");
		duplicateCharCount("Better"); 
	}
	
	static void duplicateCharCount(String inputString)
    {
		 HashMap<Character, Integer> charCountMap = new HashMap<Character, Integer>();
		 
		 //Convert String to char array
		 char[] strArray = inputString.toCharArray();
		 
		 for (char c : strArray)
	     {
			 if(charCountMap.containsKey(c))
			 {
				 //Increment count by one if character present in hashmap
				 charCountMap.put(c, charCountMap.get(c)+1);
			 }
			 else
			 {
				 //If char is not present then put first value as 1
				 charCountMap.put(c, 1);
			 }			 
	     }
		 
		 System.out.println("Duplicate Characters Count in String: "+inputString);
		 for (Entry<Character, Integer> entry : charCountMap.entrySet()) 
		 {
			 if(entry.getValue() > 1)
				 System.out.println(entry.getKey() + " = " + entry.getValue());
		}
    }
}

Output

Duplicate Characters Count in String: ProgramsBuzz

r = 2

z = 2

Duplicate Characters Count in String: Learn Java

a = 3

Duplicate Characters Count in String: Better

t = 2

e = 2