JAVA: How to find the frequency of elements within an ArrayList using a Hashtable


import java.util.ArrayList;
import java.util.Hashtable;

class LinkedListFreq
{
/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub

ArrayList elementList = new ArrayList();

elementList.add(“qwerty”);
elementList.add(“qwerty”);
elementList.add(“fox”);
elementList.add(“one”);
elementList.add(“7”);
elementList.add(“qwerty”);
elementList.add(“fox”);
elementList.add(“!”);

Hashtable frequencyHash = new Hashtable();

ArrayList uniqueList = new ArrayList();

for( int i = 0; i < elementList.size(); i++)
{
if (uniqueList.contains(elementList.get(i)))
{
int elementCount =
Integer.parseInt(frequencyHash.get(elementList.get(i)).toString());

elementCount++;
frequencyHash.put(elementList.get(i), elementCount);
}
else
{
uniqueList.add(elementList.get(i));
frequencyHash.put(elementList.get(i),1);
}
}
System.out.println(frequencyHash);
}
}

5 thoughts on “JAVA: How to find the frequency of elements within an ArrayList using a Hashtable

  1. Aditya

    I have a list and i want a method such that when we enter the frequency like 3 this method return an array with the elements that occur in three time

    Reply
    1. MantasCode

      Using the populated frequencyHash(element,frequency) from the main post . You can do something like this to retrieve elements from the hashtable depending on their numeric frequency.


      //enumerate through the frequencyHash
      Enumeration keys = frequencyHash.keys();
      while( keys.hasMoreElements() )
      {
      Object key = keys.nextElement();
      Object value = frequencyHash.get(key);
      //value to string
      String stringvalue = value.toString();
      //string value to int
      int frequencyNum = Integer.parseInt(stringvalue);
      //if frequency of element is 3
      if(frequencyNum == 3 )
      {
      //do something with element here.
      System.out.println(key);
      }
      }

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *