Exercises

In the section called “Result string ordering” we created a sorted set of words appearing in a text among with their respective frequencies:

  6: Newton
  6: and
  5: Einstein
  3: Pascal
  3: found
  3: meter
  3: one
  3: to
  2: a
...

Achieving this result relied on implementing a helper class WordFrequency grouping words and frequencies:

public class WordFrequency {
  /**
   * The frequency of this word will be counted.
   */
  public final String word;
  private int frequency;
...

A cleaner solution might conceive the above result output as a Map<String, Integer>. The set of words appearing in a text will be regarded as keys. The frequencies of appearance are corresponding values:

Map<String, Integer>
Word (String) Frequency (Integer)
Newton 6
and 6
Einstein 5
Pascal 3
... ...

exercise No. 198

Implementing word frequencies by Map<String, Integer> instances.

Q:

Re-implement the section called “Result string ordering” replacing your WordFrequency object by an instance of Map<String, Integer>. For the time being consider the output sorting order yet as irrelevant.

A:

The subsequent exercise is considered to be optional with respect to the final course's examination. It does however provide some deeper insight into the subject of Map instances.

exercise No. 199

Regain sorting capabilities.

Q:

Refine Implementing word frequencies by Map<String, Integer> instances. to sort your output by word frequencies in the first place as you already did in the section called “Result string ordering”.

Hint: Following the discussion in Sorting the Map<Key,Value> in descending order based on the value you may create a List<Entry(<String, Integer>> from your Map<String, Integer> instance on demand (i.e. when sorting). Then define an appropriate Comparator class to get this list sorted.

A: