Best practice to find Duplicate Character from a String in java
This program could be the best way to find the number of duplicate characters from the given String. Here we are using Map and Set from java.util.Collections package. In the below program we are using Set to collect different characters from the given String. One boolean variable and one method named as findDuplicateChar(String myString) to find the duplicates. Also some known methods like toCharArray() to convert String to character array and for-each loop to iterate Set and Array. Better you can go through the given program to find duplicate characters from the given String.
Program:
Output:
Reference Books:
Program:
import java.util.HashMap; import java.util.Map; import java.util.Set; /** * @author javabynataraj.blogspot.com * */ public class FindDuplicateCharFromString { Map<Character, Integer> allDuplicate; // Returns a Set view of the keys contained in this map Set<Character> Keys; static boolean amIDuplicate; public static boolean isAmIDuplicate() { return amIDuplicate; } public void setAmIDuplicate(boolean amIDuplicate) { FindDuplicateCharFromString.amIDuplicate = amIDuplicate; } public static void main(String a[]) { System.out.println(" **** http://javabynataraj.blogspot.com **** "); FindDuplicateCharFromString object = new FindDuplicateCharFromString(); // Test1 object. findDuplicateChar("javabynataraj blog"); System.out.println("Any Duplicate Char? " + isAmIDuplicate()); // Test2 object. findDuplicateChar("no duplicate"); System.out.println("Any Duplicate Char? " + isAmIDuplicate()); } public void findDuplicateChar(String mySting) { allDuplicate = new HashMap<Character, Integer>(); Keys = allDuplicate.keySet(); setAmIDuplicate(false); char[] charArr = mySting.toCharArray(); // Iterate through String for (Character myChar : charArr) { if ( allDuplicate.containsKey(myChar)) { // Just increment counter if Character presents allDuplicate.put(myChar, allDuplicate.get(myChar) + 1); } else { allDuplicate.put(myChar, 1); } } System.out.println("n========== Let's print all results. Here is a String: "+ mySting + " =========="); for (Character myChar : Keys) { if ( allDuplicate.get(myChar) > 1 && allDuplicate != null) { setAmIDuplicate(true); System.out.println("Character " + myChar + " appeared " + allDuplicate.get(myChar) + " times"); } } } }
Output:
Reference Books:
- Core Java for Beginners 2nd Edition by Das
- Java Generics and Collections
- Core Java Advanced Features (English) 9th Edition
- Core Java, Volume I : Fundamentals 9th Edition