I am currently writing a word counter program which will use a Hashtable
to count the words in a file and I would like to create a linked list within the program to sort the words' occurrence in descending order.
I know how to add elements to a linked list but I don't know how to add elements from a Hashtable
to a linked list and sort the values in descending order. Can you please help with that?
Here is the code I have so far:
import java.io.FileReader;
import java.util.*;
import java.util.Hashtable;
import java.util.stream.Collectors;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class WordCounter {
public Hashtable count_words(String contents) {
Hashtable < String, Integer > count = new Hashtable < String, Integer > ();
Set < String > key = count.keySet();
StringTokenizer w = new StringTokenizer(contents);
while (w.hasMoreTokens()) {
String word = w.nextToken();
word = word.toLowerCase();
word = word.replaceAll("[-+.^:(\"),']", "");
if (count.containsKey(word)) {
count.put(word, count.get(word) + 1);
} else {
count.put(word, 1);
}
}
return count;
}
public LinkedList top20(Hashtable count) {
///I don't know how to add elements from hashtable to linkedlist
return new LinkedList();
}
public static void main(String args[]) {
try {
String contents = "";
Scanner in = new Scanner(new FileReader("src/ADayInTheLife.txt"));
while ( in .hasNextLine()) {
contents += in .nextLine() + "\n";
}
WordCounter wc = new WordCounter();
Hashtable count = wc.count_words(contents);
System.out.println(count);
} catch (Exception e) {
System.err.println("Error " + e.getMessage());
}
}
}