Java Reference
In-Depth Information
somewhat haphazard order. A TreeMap can store only comparable data and performs
a bit slower, but it keeps its keys in sorted order.
We could store the social security number information from the previous section
in a TreeMap as follows:
Map<Integer, String> ssnMap = new TreeMap<Integer, String>();
ssnMap.put(867530912, "Jenny");
ssnMap.put(239876305, "Stuart Reges");
ssnMap.put(504386382, "Marty Stepp");
System.out.println(ssnMap);
The keys would be ordered differently, leading to the following output when printing
the map:
{239876305=Stuart Reges, 504386382=Marty Stepp, 867530912=Jenny}
Notice that the social security numbers (the map's keys) are sorted in numeric
order. This sorting can be useful for certain applications, but HashMap is still the fla-
vor Sun recommends for general use over TreeMap . Many applications don't care
about the order of the keys and benefit from the better performance of HashMap .
HashMap works even on data that does not have a natural ordering.
Map Case Study: WordCount
In an earlier example, we counted the number of unique words in the topic Moby
Dick. What if we wanted to find the words that occur most frequently in the topic? To
do this, we should count how many times each word in the topic occurs, then exam-
ine all of those counts and print the ones with the largest values.
Maps are very useful for solving these kinds of problems. We can create a word-
count map in which each key is a word and its associated value is the number of
occurrences of that word in the topic:
wordCountMap = empty.
for (each word from file) {
if (I have never seen this word before) {
set this word's count to 1.
} else {
increase this word's count by one.
}
}
We'll need a Scanner to read the appropriate file and a Map to store the word
counts. We'll use a TreeMap so that the frequently used words will be shown in
alphabetical order:
Map<String, Integer> wordCountMap = new TreeMap<String, Integer>();
Scanner in = new Scanner(new File("mobydick.txt"));
 
Search WWH ::




Custom Search