Java中将Key和Value加入优先队列并按Key排序

Java中将Key和Value加入优先队列并按Key排序

本文介绍了Java中将Key和Value加入优先队列并按Key排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试接收字符串列表并将它们添加到具有键和值的优先级队列中.Key 是单词,value 是单词的字符串值.然后我需要先对具有最高字符串值的队列进行排序.优先级队列不允许我添加 2 个值.

I am trying to take in a List of strings and add them into a Priority Queue with Key and Value. The Key being the word and the value being the string value of the word. Then I need to sort the queue with the highest string value first. The priority queue is not letting me add 2 values.

public static List<String> pQSortStrings(List<String> strings) {
    PriorityQueue<String, Integer> q = new PriorityQueue<>();

    for (int x = 0; x < strings.size(); x++) {
        q.add(strings.get(x),calculateStringValue(strings.get(x)));
    }
    return strings;
}

推荐答案

问题

PriorityQueue 可以在它的每个节点中存储单个对象.因此,您尝试做的事情不能按原样完成.

Problem

PriorityQueue can store a single object in it's each node. So what you are trying to do can not be done as it is.

但是您可以将两个对象组合在一个类中,然后使用 PriorityQueue.

But you can compose both objects in a single class and then use the PriorityQueue.

您要么需要提供 比较器或依赖自然排序 通过实施 Comparable 界面.

You would either need to supply a Comparator or rely on natural ordering by implementing Comparable interface.

  • 创建一个以 Stringint 作为其成员的类.

  • Create a class which has String and int as it's members.

public class Entry {
    private String key;
    private int value;

    // Constructors, getters etc.
}

  • 实现Comparable接口并将比较委托给String.

    public class Entry implements Comparable<Entry> {
        private String key;
        private int value;
    
        public Entry(String key, int value) {
            this.key = key;
            this.value = value;
        }
    
        // getters
    
        @Override
        public int compareTo(Entry other) {
            return this.getKey().compareTo(other.getKey());
        }
    }
    

  • 使用这个类构建PriorityQueue.

    PriorityQueue<Entry> q = new PriorityQueue<>();
    

  • 添加元素如下.

  • Add elements as following.

    q.add(new Entry(strings.get(x), calculateStringValue(strings.get(x))));
    

  • 希望这会有所帮助.

    这篇关于Java中将Key和Value加入优先队列并按Key排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    09-02 11:04