简体   繁体   中英

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.

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

以下是高级步骤: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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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