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

Our sample solutions are as follows.

In FrequencyCounter

   /**
    * Creates a new empty HashMap, then populates the map with 
    * entries whose keys are the distinct items found in the argument,
    * and whose values are Integer objects that represent the number
    * of times the corresponding item is found.
    * @param    list   the list.
    * @return   the populated HashMap
    *
    */
   public Map<Object,Integer> countFrequencies(List<?> list)
   {
      Map<Object,Integer> count = new HashMap<Object,Integer>();
       
      for (Object element : list)
      {
         if (!count.containsKey(element))
         {
            count.put(element, 1);
         }
         else
         {
            count.put(element, count.get(element) + 1);
         }
      }
      return count;      
   }

In FrequencyTest (new code is shaded)

public static void main(String[] args) throws Exception
{
   ObjectInputStream ois1 = new ObjectInputStream(new FileInputStream("Chapter_1"));
   Object obj = ois1.readObject();
   List<?> list1 = (ArrayList<?>)obj;
    FrequencyCounter fc = new FrequencyCounter();
    Map result = fc.countFrequencies(list1);
 
    System.out.println(result.get("Bennet"));
    System.out.println(result.get("four"));
    System.out.println(result.get("see"));
    System.out.println(result.get("good-humoured"));
    System.out.println(result.get("them"));
}

Expected Results

6
2
4
1
9