1.

Given a para containing 200 words, you need to find the count of each word occurring in the para. How will you go about this? Explain the reason for choosing a particular collection and its working in detail.

Answer»

In this case, we NEED to iterate over words in the paragraph (separated by space). As we iterate we need to maintain unique elements in the paragraph along with their count. A simple HashMap is WELL suited for this scenario.

A HashMap is a part of the Java Collections framework and implements the MAP interface. Elements are stored as KEY-value pair. Each key in the map will be unique. Order of insertion of elements is however not maintained. To access a value in a hashmap one must know the corresponding key. If the key is known, it allows us to store an object or retrieve it in constant time – O (1).

To solve the above problem we first split the paragraph by space into a string ARRAY. Next, we iterate over elements in this array and check if the element is already present in hashmap or not. If element is not found, then a new entry is created in a hashmap with count 1, else if the element is found then the corresponding count is updated.

Once the array has been traversed we have unique elements as well as their count on the map. Now we simply need to traverse the hashmap and output each as well as corresponding value. This will give us the unique element is the paragraph as well as the number of times it occurred.



Discussion

No Comment Found