简体   繁体   English

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

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

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. 我目前正在编写一个单词计数器程序,该程序将使用Hashtable对文件中的单词进行计数,并且我想在该程序中创建一个链接列表,以按降序对单词的出现进行排序。

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. 我知道如何将元素添加到链表中,但是我不知道如何将Hashtable表中的元素添加到链表中并按降序对值进行排序。 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());
    }
  }
}

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

One possible solution is to use lambda, in this example there is no need to convert from Hash to LinkedList, just using the Hash to sort and list the first 20 in reverse order: 一种可能的解决方案是使用lambda,在此示例中,无需从哈希表转换为LinkedList,只需使用哈希表以相反的顺序排序和列出前20个:

Try with this approach: 尝试使用这种方法:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM