Working with Maps
Terminology
- Definition
- A map is an unordered collection of values each with distinct
keys. The key-value pair stored within the map is called an entry.
- The key is a distinct object that represents the entry as a whole.
- The value is any object.
- A map is sometimes also called a dictionary.
- The key is a distinct object that represents the entry as a whole.
Using Maps
A Map might be used to associate student IDs with complete student records, or
words to their definitions (like a real dictionary). What other examples of
maps can you think of?
What kind of collection do you think would be used to store the keys in a map?
What kind of collection do you think would be used to store the values in a map?
Using TreeMap
In Java, the class
TreeMap,
is used to model the concept of a map given above. In the remainder of this
activity, you will use one or more
TreeMap objects to discover several interesting statistics about words in a file: how
many times a word appears in a given file, or on which lines a word appears in
a file.
There is one class defined for this activity: WordLines. You should start by reading over the code in this class and making sure you understand it. In particular, explain the following details about the code:
- What is the purpose of the
Integerobject and how is it used in this class? - Why is the output printed in sorted order?
- How does the method
printResultswork for any kind of map (i.e., why is the?character required instead of simply using the superclassObject)?
Problems
After you understand the current implementation, you should implement the following additional methods and test them by inspecting their output.
- Complete the method,
getLineNumbers, that creates a newMapwith words as the key and the set of line numbers on which that word appears as the value. This method should get the data for each word from theScannerpassed it. - Complete the method,
getFrequencies, that creates a newMapwith letters as the key and the set of words which start with that letter as the value. This method should get the data for each word from theScannerpassed it.