Question: Read all words from a file and add them to a map whose keys are word lengths and whose values are comma-separated strings of words
Read all words from a file and add them to a map whose keys are word lengths and whose values are comma-separated strings of words of the same length. Then print out those strings, in increasing order by the length of their entries.
Provide two versions of your solution, one that uses the merge method (see Special Topic 15.1) and one that updates the map as in Worked Example 15.1.
Data from special topic 15.1

Data from worked example 15.1.





Special Topic 15.1| Updating Map Entries Maps are commonly used for counting how often an item occurs. For example, Worked Example 15.1 uses a Map to track how many times a word occurs in a file. It is a bit tedious to deal with the special case of inserting the first value. Consider the fol- lowing code from Worked Example 15.1: Integer count = frequencies.get(word); // Get the old frequency count // If there was none, put 1; otherwise, increment the count if (count == null) { count = 1; } else { count count + 1; } frequencies.put (word, count); This task can be simplified with the merge method of the Map interface. You specify A key. A value to be used if the key is not yet present. A function to compute the updated value if the key is present. The function is specified as a lambda expression (see Special Topic 10.4). For example, frequencies.merge (word, 1, (oldValue, no tPresent Value) -> oldValue + not PresentValue); does the same as the four lines of code above. If word is not present, the value is set to 1. Other- wise, the old value is incremented. The merge method is also useful if the map values are sets or comma-separated strings-see Exercises E15.6 and .. E15.7.
Step by Step Solution
3.42 Rating (161 Votes )
There are 3 Steps involved in it
The task is to read words from a file and compile them in a Map where the keys are word lengths and the values are strings made up of commaseparated w... View full answer
Get step-by-step solutions from verified subject matter experts
