This program going to find out the number of duplicate characters in the given String. In this program we are using Map and Set from java.util.Collections package and one method named as findDuplicate(String str) to find the duplicates.
Java Program to Find Duplicate Characters in a String
import java.util.HashMap; import java.util.Set; import java.util.Map; public class FindDuplicateChar { public void findDuplicate(String str) { Map<Character, Integer> map = new HashMap<Character, Integer>(); char[] chars = str.toCharArray(); for(Character ch:chars) { if(map.containsKey(ch)) { map.put(ch, map.get(ch)+1); } else { map.put(ch, 1); } } Set<Character> keys = map.keySet(); for(Character ch:keys) { if(map.get(ch) > 1) { System.out.println("Char "+ch+" "+map.get(ch)); } } } publicstaticvoid main(String args[]) { FindDuplicateChar fdc = new FindDuplicateChar(); System.out.println("tutorialspoint4all.com"); System.out.println("-------------------------"); fdc.findDuplicate("tutorialspoint4all.com"); } }
Output:-