View the step-by-step solution to:


This code stores the words from a file into a single List, and is the same as

from last week. Note the stub method getWordCounts. Fill in the code for this method so that it builds a Map that contains word/count pairs - when the code is finished, each word should be a key in the map associated with a count of the number of times that word occurs in the file. Modify the main loop so that it iterates over the keys in the Map and displays the counts of each word in the file.

The stub in getWordCounts uses a HashMap.  Notice the ordering of the elements displayed to the screen. Now modify getWordCounts to use a TreeMap. How are the results from using a HashMap and TreeMap different? answer in the comments at the top of the program.


Suppose we want to keep track of the words in a file organized by how many occurrences of the word there are in the file (rather than alphabetically). For example, we want to know how many words only occur one time in the whole file, or which word occurs the most times. 

In a standard Map this won't work - each key must have exactly one associated value. However, we can use a slightly modified map known as a multimap to get this behavior. In Java, implementing a multimap is easy - we just use a standard Map object but store a List as the value. If we want to add an element to the Map for a key that is already in the Map, we get the LinkedList associated with that key and add the element to it. If we want to add a new key, we new LinkedList for it and store it in the Map.

Make a copy of your solution to Exercise 1 and name it Add a method that takes the map that the method getWordCounts creates as a parameter and returns a Map<Integer,List<String>> to keep track of word counts in this fashion. Then for each count in the multimap, display a single line showing the number followed by the list of words with that count in the file. Try it with a HashMap and a TreeMap as the underlying data structure - when would we prefer to use a TreeMap over a HashMap for this purpose?

Recently Asked Questions

Why Join Course Hero?

Course Hero has all the homework and study help you need to succeed! We’ve got course-specific notes, study guides, and practice tests along with expert tutors.

  • -

    Study Documents

    Find the best study resources around, tagged to your specific courses. Share your own to gain free Course Hero access.

    Browse Documents
  • -

    Question & Answers

    Get one-on-one homework help from our expert tutors—available online 24/7. Ask your own questions or browse existing Q&A threads. Satisfaction guaranteed!

    Ask a Question
Ask Expert Tutors You can ask You can ask ( soon) You can ask (will expire )
Answers in as fast as 15 minutes