Showing posts with label Repeated characters in Java. Show all posts
Showing posts with label Repeated characters in Java. Show all posts

Find Repeated Characters, Find unique Characters using Hashmap

package packageName;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.Map;

 

public class countDuplicates_FinduniqueUsingHashmap {

 

       public static void main(String[] args) {

            

             String str = "asdfSdfogdFzgjknEswsAawm";

             int l = str.length();

             String s = "";

             Map<String,Integer> map = new HashMap<String,Integer>();

             ArrayList<String> uniqueChars = new ArrayList<String>();

             for(int i=0; i<l;i++) {

                    s = Character.toString(str.charAt(i));

                    if(map.containsKey(s)) {

                           map.put(s, map.get(s)+1);

                    } else {

                           map.put(s, 1);

                           uniqueChars.add(s);// not correct way to get unique chars

                    }

             }

             System.out.println(map); //Output:  {a=2, A=1, d=3, E=1, f=2, F=1, g=2, j=1, k=1, m=1, n=1, o=1, s=3, S=1, w=2, z=1} correct

             String smallchar = str.replaceAll("[^a-z]","");

             System.out.println("small chars are "+smallchar); //Output:  asdfdfogdzgjknswsawm

             int hashMapSize = map.size(); //Output:  13 correct

             System.out.println("Hashmap Size is "+hashMapSize); //Output:  13 correct

 

//Find UNIQUE CHARS

             for(Map.Entry<String,Integer> entry : map.entrySet()) {

                    if(entry.getValue().equals(1)) {

                           System.out.println("the key having the value 1 : "+entry.getKey()); 

                    }

             }

             System.out.println("Unique chars "+uniqueChars); //Output:  [a, s, d, f, o, g, z, j, k, n, e, w, m] not correct

       }

 

}

 

/* Output

the key having the value 1 : A

the key having the value 1 : E

the key having the value 1 : F

the key having the value 1 : j

the key having the value 1 : k

the key having the value 1 : m

the key having the value 1 : n

the key having the value 1 : o

the key having the value 1 : S

the key having the value 1 : z   */