Java.是否可以在优先级队列中使用一对,然后使用键作为优先级返回值

编程入门 行业动态 更新时间:2024-10-24 12:22:04
本文介绍了Java.是否可以在优先级队列中使用一对,然后使用键作为优先级返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

So I want to use the smallest key as the priority and then return the VALUE of that corresponding key:

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

Im寻找的输出为90,因为1是最小键.即使将值用作优先级并返回键也可以,因为我可以根据需要交换数据.我想使用值/键作为优先级显示键/值(在这种情况下为最小值).我不知道在这种情况下如何做到这一点.在C ++中可以正常工作.

The output Im looking for is 90 because 1 is the smallest key. Its fine even if the value is used as the priority and the key is returned because I can just swap the data if neccessary. I want to display key/value using value/key as a priority (minimum value in this case). I do not know how this can be done in this scenario. This works fine in C++.

推荐答案

您需要使用比较器,它将用于订购此优先级队列.

You need to use Comparator which will be used to order this priority queue.

在创建 PriorityQueue

PriorityQueue<Pair<Integer,Integer> > pq= new PriorityQueue<Pair<Integer,Integer>>(n, Comparatorparing(Pair::getKey));

您可以使用lambda表达式

You can use lambda expression

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

更多推荐

Java.是否可以在优先级队列中使用一对,然后使用键作为优先级返回值

本文发布于:2023-10-30 11:42:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1542750.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:优先级   队列   返回值   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!