-11

How to Print number of occurrences of each word of a text file along with the word by reading the file.

For example, A file with name "test.txt" having some contents suppose, "Lion is the king of Forest. Lion runs slower than a tiger"

  1. first read the file "test.txt". by using any stream classes of java.

  2. Print each word along with number of occurrences of that word. For example., In this file "Lion" is twice times so output should be like-> Lion:2

Similarly, king appears only one time so it should print like-> king:1.

  1. Can it be done by HashMap ? if So please solve this.

1 Answers1

0
  1. Read a line: Read String line by line in Java
  2. Split each line using a space character: Java split string to array
  3. The result of #2 will give you an array of String Objects.
  4. Use the HashMap data structure (stores a key/value pair) to store each element:

     HashMap hashMap = new HashMap();
     hashMap.put(key, value); ie. hashMap.put(array[0], 0)
    
  5. Iterate through the map each time you try to add an element. If the key exists, increment the value pair. Otherwise, put the new element in.

  6. Print the HashMap.
Community
  • 1
  • 1
Abdulgood89
  • 359
  • 2
  • 9