patternjavaMinor
File Parsing in Java Using Collection
Viewed 0 times
filecollectionjavaparsingusing
Problem
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.
/* 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 wordList = new ArrayList();
Map wordCount = new HashMap();
while (s.hasNext())
{
wordList.add(s.next());
}
HashSet hset = new HashSet(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);
}
}Solution
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)
}Code Snippets
while (scanner.hasNext()) {
String word = scanner.next()
Integer count = wordCount.get(word)
wordCount.put(word, count == null ? 1 : ++count)
}Context
StackExchange Code Review Q#114958, answer score: 3
Revisions (0)
No revisions yet.