Activity 5.9 - Developing a word frequency counter using a List and a HashMap

Topic

In this activity we develop a class FrequencyCounter with a method countFrequencies(List) that accepts a list in which some items may be repeated and counts the number of times each item appears.

Materials

In addition to the Solution document, the project for this activity contains the following:

You have also been provided with a data file named Chapter_1.

Task

The class FrequencyCounter is to fulfil the following specification:

Map<Object,Integer> countFrequencies(List<?> list)

This is a public method that accepts a list argument, creates a new empty HashMap, then populates the map with entries whose keys are the distinct items found in the list, and whose values are Integer objects representing the number of times the corresponding item is found in the list. For example if the argument is:

[a, b, r, a, c, a, d, a, b, r, a]

the map returned should be:

{b=2, a=5, r=2, d=1, c=1}

(The exact order in which the entries appear may differ from this.)

Note that the list argument is specified with a wildcard operator ?, which means that the method will accept a list of any type.

The method performs the following steps:

Instructions

  1. Write code for the method countFrequencies, carefully following the specification above.

  2. Class FrequencyTest contains code that reads in the first chapter of Pride and Prejudice from a data file and stores the words in an ArrayList<?> list1. Now you are to insert code in the main method which will do the following:

    When you have made these changes, run the project and check the output.