Just as Python provides the dictionary when we want to have easy access to key-value pairs, Java also provides us a similar mechanism. Rather than the dictionary terminology, Java calls these objects Maps. Java provides two different implementations of a map, one is called the TreeMap and the other is called a HashMap. As you might guess the TreeMap uses a balanced binary tree behind the scenes, and the HashMap uses a hash table.
Lets stay with a simple frequency counting example, only this time we will count the frequency of words in a document. Listingย 3.6.1 shows a simple Python program for how this could look.
This program reads the file alice30.txt in Dataย 3.6.2, and it then splits it into a list of words. Next it creates a dictionary called count which maps each word to the number of times that word occurs in the text. Finally, it prints out the words in alphabetical order along with their frequency.
Data3.6.2.Data file for testing the word frequency program.
Data: alice30.txt
Down, down, down. Would the fall NEVER
come to an end! 'I wonder how many
miles I've fallen by this time?' she
said aloud. 'I must be getting somewhere
near the centre of the earth. Let me see:
that would be four thousand miles down,
I think--' (for, you see, Alice had
learnt several things of this sort in
her lessons in the schoolroom, and though
this was not a VERY good opportunity for
showing off her knowledge, as there was no
one to listen to her, still it was good
practice to say it over) '--yes, that's
about the right distance--but then I
wonder what Latitude or Longitude I've got
to?' (Alice had no idea what Latitude was,
or Longitude either, but thought they were
nice grand words to say.)
Rearrange the blocks to create a general Java method that accepts a dictionary (Map) of item prices and updates the price of a specific item. If the item does not exist, do nothing.