File Parsing in Java Using Collection I have the following requirements:


  /* Collection
  
  Write a program that counts the number of unique words in a large text file.
  
  a] Store the words in a collection and report the number of unique words.
  
  b] Once you have created the collection, allow the user to search it to see whether various words appear in the text file and to get the count if present
  
  */


I have implemented the following code to satisfy the above requirements. Please review the code and give suggestions to make this code more clear,  exactly correct and optimized.

import java.util.*;
import java.io.*;
public class test5
{
    public static void main(String[]args) throws FileNotFoundException
    {

        Scanner s = new Scanner(new File("test.txt"));
        ArrayList&lt;String&gt; wordList = new ArrayList&lt;String&gt;();
        Map&lt;String, Integer&gt; wordCount = new HashMap&lt;String, Integer&gt;();        

        while (s.hasNext())
        {
            wordList.add(s.next());
        }

        HashSet&lt;String&gt; hset = new HashSet&lt;String&gt;(wordList);

        System.out.println("Count of Unique words from file is: "+hset.size());

        for(String word: wordList)
        {
            Integer count = wordCount.get(word);          
            wordCount.put(word, (count==null) ? 1 : count+1);
        }
        System.out.println(wordCount);
    }
}
Your code looks overly complex to me, using three different collections when one, the hash map, would be enough. Use your code from the wordList loop when emptying the scanner, and update the word count there:

while (scanner.hasNext()) {
    String word = scanner.next()
    Integer count = wordCount.get(word)
    wordCount.put(word, count == null ? 1 : ++count)
}