• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Paul Clapham
  • Devaka Cooray
  • Bear Bibeault
Sheriffs:
  • Junilu Lacar
  • Knute Snortum
  • Liutauras Vilda
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Piet Souris
Bartenders:
  • salvin francis
  • Carey Brown
  • Frits Walraven

Array elements frequency count using hashmap

 
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.
 
Marshal
Posts: 68859
275
  • 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);
}
}
 
Rancher
Posts: 2265
20
Android Java ME Eclipse IDE Java
  • 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
Marshal
Posts: 68859
275
  • 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.
 
If you're gonna buy things, buy this thing and I get a fat kickback:
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
    Bookmark Topic Watch Topic
  • New Topic