• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Array elements frequency count using hashmap

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 79239
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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);
}
}
 
Bartender
Posts: 2270
20
Android Java ME Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 79239
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic