如何将元素从 HashTable 添加到 LinkedList 并对其进行排序?

How to add elements to a LinkedList from HashTable and sort them?

我目前正在编写一个单词计数器程序,它将使用 Hashtable 来计算文件中的单词,我想在程序中创建一个链表以降序排列单词的出现.

我知道如何将元素添加到链表,但我不知道如何将 Hashtable 中的元素添加到链表并按降序对值进行排序。你能帮忙吗?

这是我目前的代码:

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());
    }
  }
}

这是高级步骤 1) 定义一个具有属性 word 和 count 的 LinkNode 以及对 LinkNode 的自引用作为下一个 2) 定义一个方法,将 return 引用到 LinkNode 的头部 3) 在方法中迭代哈希 table 并执行以下活动 a) 如果链接列表为空 创建一个带有单词和计数值的 LinkNode 并将其指定为 LinkList 的头部 b) 否则 您需要找到要插入新节点的位置(遍历节点并将计数与列表中的节点进行比较以根据您的顺序决定) 3) 可以return构造头节点

一种可能的解决方案是使用lambda,在这个例子中不需要从Hash转换为LinkedList,只需使用Hash排序并倒序列出前20个:

试试这个方法:

Hashtable<String,Integer> count = wc.count_words(contents);

count.entrySet().stream().sorted(Map.Entry.<String,Integer> comparingByValue().reversed()).limit(20).forEach(System.out::println);