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<String> wordList = new ArrayList<String>();
Map<String, Integer> wordCount = new HashMap<String, Integer>();
while (s.hasNext())
{
wordList.add(s.next());
}
HashSet<String> hset = new HashSet<String>(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);
}
}