• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array elements frequency count using hashmap

 
Ambreen Khanam
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Go through the Java Tutorials about maps, and you will find they have provided a very similar program as an example.
 
Ambreen Khanam
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1603
5
Android Java Java ME
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic