Search code examples
data-structuresfrequencysortedlist

Best data structure for maintaining a list of object-types sorted by frequency


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>();