Saturday 23 November 2013

Program to find frequency of elements in a String array.

One of the common interview questions is "Find how frequently a particular String element occurs in a String array".
Through this question the interviewers try to test your knowledge of Collections API.

The algorithm that we will try to use is as follows:

1. Initialize the string array
          String strArray[] = {"Amit","Suresh","Suyash","Vimal","Amit","Amit","Suyash","Amit","amit"};

2. Initialize a TreeMap
          Map<String, Integer> map = new TreeMap<String,Integer>();

    There must be one question popping in ur head- Why the hell does he want to use a MAP ????
    Well !!!
    I want to use Map because Map allows you to store key value pairs. I will store the String as key and           its frequency as the value. Well you also do the other way round- store String as value and its frequency       as key. But you won't succeed because Java doesn't allow you to modify keys in a Map.

3. You can search if a particular String is present in the Map
    To do that you will have to iterate over the Map.
    But Map interface doesn't provide you with an Iterator. Don't worry !!! There is workaround. We can           convert Map to a Set of Entries(that contain key value pairs).
                Set<Entry<String,Integer>> entrySet = map.entrySet();

   Then obtain the iterator over the set. I have obtained an Iterator object that iterates over                                 Entry<String,Integer>.
                Iterator<Entry<String,Integer>> it = entrySet.iterator();

    If it is present then increment its frequency. If  it is not already there then simply add it to the Map and set       its frequency as 1 as it has occurred for the first time.

4. Print the Map.
        System.out.println(map);


Program in Java
package mypackage;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

public class Test5 {

public static void main(String[] args) {

//Program to count the frequency of a word in an array
//Initialize the array
String strArray[] = {"Amit","Suresh","Suyash","Vimal","Amit","Amit","Suyash","Amit","amit"};
Map<String, Integer> map = new TreeMap<String,Integer>();
for (String string : strArray) {
if(map.containsKey(string)){
Set<Entry<String,Integer>> entrySet = map.entrySet();
Iterator<Entry<String,Integer>> it = entrySet.iterator();
while (it.hasNext()) {
Entry<String,Integer> entry = (Entry<String,Integer>) it.next();
if(entry.getKey().equals(string)){
int value = (int) entry.getValue();
entry.setValue(++value);
}
} //while ends
} //if ends

else
map.put(string,1);
} //for ends

System.out.println(map);
}//main ends
}//class ends


Output:
{Amit=4, Suresh=1, Suyash=2, Vimal=1, amit=1}

Note you can also use a HashMap. The program I have shown will  work for both TreeMap as well       as HashMap. If you use HashMap you will get the following output.

{Suresh=1, Vimal=1, Amit=4, Suyash=2, amit=1}

The only difference in output is the order in which map elements are printed. In TreeMap the keys were sorted in the ascending order while in HashMap there is no such sorting based on key values. 

Thats it guys. Signing off for today. Happy Learning.

1 comment:

  1. Hi Riz,

    Same output using traditional coding style(without using collections framework)
    String strArray[] = {"Amit","Suresh","Suyash","Vimal","Amit","Amit","Suyash","Amit","amit"};
    System.out.print("{");
    for(int i=0; i=0; j--){
    if(temp.equals(strArray[j])){
    skip=true;

    }

    }
    for(int k=i+1; k<strArray.length; k++){

    if(temp.equals(strArray[k]) && !skip){
    count++;
    }
    }
    if(!skip){
    System.out.print(temp+"="+count+", ");
    }

    }
    System.out.print("}");

    ReplyDelete