如何在优先级队列中使用Pair,然后使用键作为优先级返回值 [英] How to use pair in a priority queue and then return the value using the key as the priority

查看:56
本文介绍了如何在优先级队列中使用Pair,然后使用键作为优先级返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想使用最小的键作为优先级,然后返回相应键的值:

import javafx.util.Pair;
import java.util.PriorityQueue;

public class Test
{
    public static void main (String[] args)
    {
        int n = 5;

        PriorityQueue <Pair <Integer,Integer> > l = new PriorityQueue <Pair <Integer,Integer> > (n);

        l.add(new Pair <> (1, 90));
        l.add(new Pair <> (7, 54));
        l.add(new Pair <> (2, 99));
        l.add(new Pair <> (4, 88));
        l.add(new Pair <> (9, 89));

        System.out.println(l.poll().getValue()); 
    }
}
我要查找的输出是90,因为1是最小的密钥。即使将值用作优先级并返回密钥也没问题,因为如果需要,我可以只交换数据。我希望使用值/键作为优先级来显示键/值(在本例中为最小值)。我不知道在这种情况下如何做到这一点。这在C++中运行良好。

推荐答案

您需要使用将用于对此优先级队列进行排序的Comparator

创建PriorityQueue时使用Comparator.comparing()并传递比较参数的Method reference

PriorityQueue<Pair<Integer,Integer> > pq=
                new PriorityQueue<Pair<Integer,Integer>>(n, Comparator.comparing(Pair::getKey));

您可以使用lambda表达式

PriorityQueue<Pair<Integer,Integer> > pq=
                    new PriorityQueue<Pair<Integer,Integer>>(n,(a,b) -> a.getKey() - b.getKey());

这篇关于如何在优先级队列中使用Pair,然后使用键作为优先级返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆