wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Array elements frequency count using hashmap Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Array elements frequency count using hashmap" Watch "Array elements frequency count using hashmap" New topic
Author

Array elements frequency count using hashmap

Ambreen Khanam
Greenhorn

Joined: Apr 18, 2013
Posts: 4
Hi,
Can anyone provide the optimised soln for this problem.
in an array say there are elements like A[1, 2, 4, 5, 4, 2, 1, 2]. How to caculate the frequency of each number and also print the no with the highest frequency.

This problem needs to be solved using hash map.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37926
    
  22
Go through the Java Tutorials about maps, and you will find they have provided a very similar program as an example.
Ambreen Khanam
Greenhorn

Joined: Apr 18, 2013
Posts: 4
Thanks Ritchie..

Are you talking about this example.

import java.util.*;

public class Freq {
public static void main(String[] args) {
Map<String, Integer> m = new HashMap<String, Integer>();

// Initialize frequency table from command line
for (String a : args) {
Integer freq = m.get(a);
m.put(a, (freq == null) ? 1 : freq + 1);
}

System.out.println(m.size() + " distinct words:");
System.out.println(m);
}
}
Swastik Dey
Rancher

Joined: Jan 08, 2009
Posts: 1449
    
    6

In the HashMap the key should be the number and the count should be the value. Iterate over your array, and check if that arrayelement(key) exists in the map, if not exists put that to map with a value 1, or else retrieve the existing value against that key, add 1 to that and put it back into map against that key.

Please correct me if I am wrong.

Swastik
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37926
    
  22
Ambreen Khanam wrote: . . . Are you talking about this example.
. . .
Yes. You have had some suggestions about how you will have to adapt that example to your own requirements.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Array elements frequency count using hashmap
 
Similar Threads
Frequency of elements in Array
incompatable types.
Remove duplicates in an Arrays
Marcus Green Mock #3
I need a special sort algorithm