java - 打印使用优先级队列排序的 HashMap 实例

标签 java hashmap hashtable priority-queue

我已经插入了 txt 文件的不同单词以及它们分别作为键和值在 HashMap 中重复的次数。问题是,我想使用 PQ 按降序打印 k 个最常用的单词,但是虽然似乎很容易将值插入整数优先级队列中,然后获取 k 个最大整数,但我无法弄清楚再次获取与每个值对应的键以打印它的方法(值可能不是唯一的)。一个解决方案是反转 HashMap ,但这似乎不是一个“安全”的选择。

public static void main(int k)throws IOException{

   //Create input stream & scanner
   FileInputStream file = new FileInputStream("readwords.txt");
   Scanner fileInput = new Scanner(file);

   Map<String, Integer> frequency = new HashMap<>();
   LinkedList<String> distinctWords = new LinkedList<String>();
   PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>();

   //Read through file and find the words
   while(fileInput.hasNext()){
       //Get the next word
       String nextWord = fileInput.next().toLowerCase();
       //Determine if the word is in the HashMap
       if(frequency.containsKey(nextWord)) {
           frequency.put(nextWord, frequency.get(nextWord) + 1);
       }
       else {
            frequency.put(nextWord, 1);
            distinctWords.add(nextWord);
       }


    }

    //Close
    fileInput.close();
    file.close();



}

最佳答案

可能有多种解决方案,这是我的。创建 class有两个字段;一个为String一个为 Integer 。使类实现Comparable并重写方法compareTo所以它比较 Integers .

public class WordFrequency implements Comparable<WordFrequency> {
    private String word;
    private Integer frequency;

    public WordFrequency(String word, Integer frequency) {
        this.word = word;
        this.frequency = frequency;
    }

    // descending order
    @Override
    public int compareTo(WordFrequency o) {
        return o.getFrequency() - this.getFrequency();
    }

    public Integer getFrequency() {
        return this.frequency;
    }

    @Override
    public String toString() {
        return word + ": " + frequency;
    }
}

然后,将您的 map<String, Integer> 转换为到 PriorityQueue<WordFrequency> :

PriorityQueue<WordFrequency> pQueue = frequency.entrySet().stream()
        .map(m -> new WordFrequency(m.getKey(), m.getValue()))
        .collect(Collectors.toCollection(PriorityQueue::new));

如果要打印,必须使用poll() ,否则订单不保证。

while(!pQueue.isEmpty())
        System.out.println(pQueue.poll());

关于java - 打印使用优先级队列排序的 HashMap 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56098608/

相关文章:

java - 流供应商收到错误 'stream has already been operated upon or closed'

java - myeclipse 中的 F4 快捷键及其在 IntelliJ idea 中的等效快捷键

java - 有什么方法可以将 for 循环放在 if 条件语句中作为快捷方式吗?

java - 压缩要通过 RMI 发送的 Java HashMap

java - 使用可迭代到 Hashmap 的迭代器实现 - 可能吗?

flutter - 在嵌套 map 内的列表中添加和删除值会影响所有嵌套 map

java - 在哈希表中存储和检索类的实例

java - 如何防止 APK 中的 Assets 文件被逆向工程

java - 当达到最大链长度时调整哈希表的大小