Best data structure for maintaining a list of object-types sorted by frequency
-
26-06-2021 - |
Question
So, I'm going through a long list with different types of things. Let's say that it has names of different kinds of foods. The list might look something like this:
olive potato strawberry potato potato strawberry
I want to store each object type and the number of times that object type occurs. Moreover, I cannot enumerate all of the object types in advance. I don't know what all of the foods will be beforehand.
I want to have something like this as the output:
potato (3) strawberry (2) olive (1)
Basically, a list of the object types in order of their frequency. What's the best data structure for this? Are there any built-in classes in Java that I could use that would prevent me from having to reinvent the wheel?
Solution
You can use HashMap<K,V>
Map<String,int> map = new HashMap<String,int>();
OTHER TIPS
I would use a dictionary-like structure. Then basically your algorithm would look like this:
-Begin Loop
If current element not a key in dictionary:
dictionary(element) -> 0 (Dictionary at key 'element' refers to 0)
Else:
dictionary(element)++ (increment dictionary at key)
Then you could later loop through the keys and find their frequencies.
Michael G.