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);
}
}
Great code.useful for me a lot.Lots of logic in small line of code.
Really elegant solution, nicely done.
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
How to get element From a list by providing its count
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);
}
}