Java interview may surprise you sometimes. There are so many similar questions you may get in an Interview like Create your own contains() method in java, find duplicate char from String, etc.
In this tutorial we will create simple way to find duplicate character from String.
package com.crunchify.tutorials; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * @author Crunchify.com * */ public class CrunchifyFindDuplicatesCharFromString { Map<Character, Integer> crunchifyAllDuplicate; // Returns a Set view of the keys contained in this map Set<Character> crunchifyKeys; static boolean amIDuplicate; public static boolean isAmIDuplicate() { return amIDuplicate; } public void setAmIDuplicate(boolean amIDuplicate) { CrunchifyFindDuplicatesCharFromString.amIDuplicate = amIDuplicate; } public static void main(String a[]) { CrunchifyFindDuplicatesCharFromString object = new CrunchifyFindDuplicatesCharFromString(); // Test1 object.crunchifyFindDuplicateChar("CrunchifyFindDuplicateChar"); System.out.println("Any Duplicate Char? " + isAmIDuplicate()); // Test2 object.crunchifyFindDuplicateChar("Crunchify"); System.out.println("Any Duplicate Char? " + isAmIDuplicate()); } public void crunchifyFindDuplicateChar(String mySting) { crunchifyAllDuplicate = new HashMap<Character, Integer>(); crunchifyKeys = crunchifyAllDuplicate.keySet(); setAmIDuplicate(false); char[] charArr = mySting.toCharArray(); // Iterate through String for (Character myChar : charArr) { if (crunchifyAllDuplicate.containsKey(myChar)) { // Just increment counter if Character presents crunchifyAllDuplicate.put(myChar, crunchifyAllDuplicate.get(myChar) + 1); } else { crunchifyAllDuplicate.put(myChar, 1); } } System.out.println("\n========== Let's print all results. Here is a String: " + mySting + " =========="); for (Character myChar : crunchifyKeys) { if (crunchifyAllDuplicate.get(myChar) > 1 && crunchifyAllDuplicate != null) { setAmIDuplicate(true); System.out.println("Character " + myChar + " appeared " + crunchifyAllDuplicate.get(myChar) + " times"); } } } }
Eclipse Console Result:
Just run above program as Java Application and you will see below result.
========== Let's print all results. Here is a String: CrunchifyFindDuplicateChar ========== Character a appeared 2 times Character C appeared 2 times Character c appeared 2 times Character h appeared 2 times Character i appeared 3 times Character n appeared 2 times Character r appeared 2 times Character u appeared 2 times Any Duplicate Char? true ========== Let's print all results. Here is a String: Crunchify ========== Any Duplicate Char? false