I have this code that reads and counts every word in a txt file, however I only want it to count each word on a line once, and so I'm trying to create a HashSet however I'm having trouble converting an ArrayList to a HashSet. Here's my code:
try {
List<String> list = new ArrayList<String>();
int totalWords = 0;
int uniqueWords = 0;
File fr = new File("filename.txt");
Scanner sc = new Scanner(fr);
while (sc.hasNext()) {
String words = sc.next();
String[] space = words.split(" ");
Set<String> set = new HashSet<String>(Arrays.asList(space));
for (int i = 0; i < set.length; i++) {
list.add(set[i]);
}
totalWords++;
}
System.out.println("Words with their frequency..");
Set<String> uniqueSet = new HashSet<String>(list);
for (String word : uniqueSet) {
System.out.println(word + ": " + Collections.frequency(list,word));
}
} catch (Exception e) {
System.out.println("File not found");
}
If anyone could help on why length "cannot be resolved or is not a field", and also why I have an error on "set[i]" telling me it must be resolved to a String. Thank you
[]on any non-array object.