gpt4 book ai didi

java - 如何将 HashTable 中的元素添加到 LinkedList 并对其进行排序?

转载 作者:行者123 更新时间:2023-12-02 02:39:26 24 4
gpt4 key购买 nike

我目前正在编写一个单词计数器程序,它将使用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());
}
}
}

最佳答案

一种可能的解决方案是使用 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);

关于java - 如何将 HashTable 中的元素添加到 LinkedList 并对其进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45723805/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com