How to find the word and their count from a text file is another frequently asked coding question from Java interviews. The logic to solve this problem is similar to what we have seen in how to find duplicate words in a String. In the first step you need to build a word Map by reading contents of a text File. This Map should contain word as a key and their count as value. Once you have this Map ready, you can simply sort the Map based upon values. If you don't know how to sort a Map on values, see this tutorial first. It will teach you by sorting HashMap on values. Now getting key and value in sorted should be easy, but remember HashMap doesn't maintain order, so you need to use a List to keep the entry in sorted order. Once you got this list, you can simply loop over the list and print each key and value from the entry. This way, you can also create a table of words and their count in decreasing order. This problem is sometimes also asked as to print all word and their count in tabular format.
Read more »
No comments:
Post a Comment