Java 将priorityQueue更改为max priorityQueue

Java 将priorityQueue更改为max priorityQueue,java,collections,priority-queue,Java,Collections,Priority Queue,我在Java中有整数的优先级队列: PriorityQueue<Integer> pq= new PriorityQueue<Integer>(); PriorityQueue pq=new PriorityQueue(); 当我调用pq.poll()时,我得到了最小元素 问题:如何更改代码以获得最大元素?您可以提供一个自定义的比较器对象,该对象按相反顺序排列元素: PriorityQueue<Integer> pq = new PriorityQueu

我在Java中有整数的优先级队列:

 PriorityQueue<Integer> pq= new PriorityQueue<Integer>();
PriorityQueue pq=new PriorityQueue();
当我调用
pq.poll()
时,我得到了最小元素


问题:如何更改代码以获得最大元素?

您可以提供一个自定义的
比较器
对象,该对象按相反顺序排列元素:

PriorityQueue<Integer> pq = new PriorityQueue<Integer>(defaultSize, new Comparator<Integer>() {
    public int compare(Integer lhs, Integer rhs) {
        if (lhs < rhs) return +1;
        if (lhs.equals(rhs)) return 0;
        return -1;
    }
});
PriorityQueue pq=new PriorityQueue(defaultSize,new Comparator(){
公共整数比较(整数lhs、整数rhs){
如果(左侧<右侧)返回+1;
如果(lhs等于(rhs))返回0;
返回-1;
}
});
现在,优先级队列将反转其所有比较,因此您将获得最大元素而不是最小元素

希望这有帮助

像这样怎么样:

PriorityQueue<Integer> queue = new PriorityQueue<>(10, Collections.reverseOrder());
queue.offer(1);
queue.offer(2);
queue.offer(3);
//...

Integer val = null;
while( (val = queue.poll()) != null) {
    System.out.println(val);
}
PriorityQueue queue=newpriorityqueue(10,Collections.reverseOrder());
排队。报价(1);
排队。报价(2);
排队。报价(3);
//...
整数val=null;
而((val=queue.poll())!=null){
系统输出打印项次(val);
}

Collections.reverseOrder()
提供了一个
比较器
,它可以将
PriorityQueue
中的元素按其自然顺序排序。

您可以使用
MinMaxPriorityQueue
(它是番石榴库的一部分):
. 您需要调用
pollLast()
方法,而不是
poll()

以下是Java中的最大堆示例:

PriorityQueue<Integer> pq1= new PriorityQueue<Integer>(10, new Comparator<Integer>() {
public int compare(Integer x, Integer y) {
if (x < y) return 1;
if (x > y) return -1;
return 0;
}
});
pq1.add(5);
pq1.add(10);
pq1.add(-1);
System.out.println("Peek: "+pq1.peek());
PriorityQueue pq1=新的PriorityQueue(10,新的比较器(){
公共整数比较(整数x,整数y){
如果(xy)返回-1;
返回0;
}
});
pq1.增加(5);
pq1.增加(10);
pq1.添加(-1);
System.out.println(“Peek:+pq1.Peek());

输出将为10

我刚刚在双堆排序最小值最大值上对两个比较器进行了蒙特卡罗模拟,它们得出了相同的结果:

这些是我使用过的最大比较器:

(A) 内置比较器

 PriorityQueue<Integer> heapLow = new PriorityQueue<Integer>(Collections.reverseOrder());
PriorityQueue heapLow=newpriorityqueue(Collections.reverseOrder());
(B) 自定义比较器

PriorityQueue<Integer> heapLow = new PriorityQueue<Integer>(new Comparator<Integer>() {
    int compare(Integer lhs, Integer rhs) {
        if (rhs > lhs) return +1;
        if (rhs < lhs) return -1;
        return 0;
    }
});
PriorityQueue heapLow=new PriorityQueue(new Comparator(){
整数比较(整数lhs、整数rhs){
如果(rhs>lhs)返回+1;
如果(rhs
PriorityQueue pq=new PriorityQueue(
新比较器(){
公共整数比较(整数a、整数b){
返回b-a;
}
}
);

您可以尝试使用反向符号推送元素。例如:添加a=2&b=5,然后轮询b=5

PriorityQueue<Integer>  pq = new PriorityQueue<>();
pq.add(-a);
pq.add(-b);
System.out.print(-pq.poll());
PriorityQueue pq=new PriorityQueue();
pq.添加(-a);
pq.添加(-b);
系统输出打印(-pq.poll());
一旦您轮询了队列的头,请将您的使用标志反转。
这将打印5(较大的元素)。可以在朴素的实现中使用。绝对不是一个可靠的解决方案。我不推荐使用它。

您可以从Java8开始使用lambda表达式

下面的代码将打印10,越大

// There is overflow problem when using simple lambda as comparator, as pointed out by Фима Гирин.
// PriorityQueue<Integer> pq = new PriorityQueue<>((x, y) -> y - x);

PriorityQueue<Integer> pq =new PriorityQueue<>((x, y) -> Integer.compare(y, x));

pq.add(10);
pq.add(5);
System.out.println(pq.peek());
//使用简单lambda作为比较器时存在溢出问题,正如ФааГааа所指出的那样。
//PriorityQueue pq=新的PriorityQueue((x,y)->y-x);
PriorityQueue pq=新的PriorityQueue((x,y)->整数。比较(y,x));
pq.增加(10);
pq.增加(5);
System.out.println(pq.peek());

lambda函数将两个整数作为输入参数,相互相减,然后返回算术结果。lambda函数实现功能接口,
Comparator
。(与匿名类或离散实现相反,这是就地使用的。)

优先级队列的元素根据其自然顺序排序,或由队列构造时提供的比较器排序

比较器应该重写比较方法

int compare(T o1, T o2)
默认比较方法返回负整数、零或正整数,因为第一个参数小于、等于或大于第二个参数

Java提供的默认PriorityQueue是最小堆,如果您想要最大堆,下面是代码

public class Sample {
    public static void main(String[] args) {
        PriorityQueue<Integer> q = new PriorityQueue<Integer>(new Comparator<Integer>() {

            public int compare(Integer lhs, Integer rhs) {
                if(lhs<rhs) return +1;
                if(lhs>rhs) return -1;
                return 0;
            }
        });
        q.add(13);
        q.add(4);q.add(14);q.add(-4);q.add(1);
        while (!q.isEmpty()) {
            System.out.println(q.poll());
        }
    }

}
公共类示例{
公共静态void main(字符串[]args){
PriorityQueue q=新的PriorityQueue(新的比较器(){
公共整数比较(整数lhs、整数rhs){
如果(lhsrhs)返回-1;
返回0;
}
});
q、 增加(13);
q、 增补(4);q.add(14);q.add(-4);q.add(1);
而(!q.isEmpty()){
System.out.println(q.poll());
}
}
}

参考资料:

您可以尝试以下方法:

PriorityQueue<Integer> pq = new PriorityQueue<>((x, y) -> -1 * Integer.compare(x, y));
PriorityQueue pq=新的PriorityQueue((x,y)->-1*整数。比较(x,y));

它适用于您可能拥有的任何其他基本比较函数。

这可以通过以下Java 8中的代码实现,该代码引入了一个只接受比较器的构造函数

PriorityQueue<Integer> maxPriorityQ = new PriorityQueue<Integer>(Collections.reverseOrder());
PriorityQueue maxPriorityQ=newpriorityqueue(Collections.reverseOrder());
PriorityQueue lowers=新的PriorityQueue((o1,o2)->-1*o1.compareTo(o2));

将优先级队列更改为最大优先级队列 方法1:Queue pq=new PriorityQueue(Collections.reverseOrder()); 方法2:队列pq1=新的优先级队列((a,b)->b-a); 让我们看几个例子:

public class Example1 {
    public static void main(String[] args) {

        List<Integer> ints = Arrays.asList(222, 555, 666, 333, 111, 888, 777, 444);
        Queue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
        pq.addAll(ints);
        System.out.println("Priority Queue => " + pq);
        System.out.println("Max element in the list => " + pq.peek());
        System.out.println("......................");
        // another way
        Queue<Integer> pq1 = new PriorityQueue<>((a, b) -> b - a);
        pq1.addAll(ints);
        System.out.println("Priority Queue => " + pq1);
        System.out.println("Max element in the list => " + pq1.peek());
        /* OUTPUT
          Priority Queue => [888, 444, 777, 333, 111, 555, 666, 222]
          Max element in the list => 888
          ......................
           Priority Queue => [888, 444, 777, 333, 111, 555, 666, 222]
           Max element in the list => 888

         */


    }
}
公共类示例1{
公共静态void main(字符串[]args){
List ints=Arrays.asList(222555666333111888777444);
Queue pq=新的优先级队列(Collections.reverseOrder());
pq.addAll(ints);
System.out.println(“优先级队列=>”+pq);
System.out.println(“列表中的最大元素=>”+pq.peek());
系统输出打印项次(…………);
//另一种方式
队列pq1=新的优先级队列((a,b)->b-a);
pq1.添加所有(ints);
System.out.println(“优先级队列=>”+pq1);
System.out.println(“列表中的最大元素=>”+pq1.peek());
/*输出
优先级队列=>[88844477773131111555666222]
列表中的最大元素=
PriorityQueue<Integer> lowers = new PriorityQueue<>((o1, o2) -> -1 * o1.compareTo(o2));
public class Example1 {
    public static void main(String[] args) {

        List<Integer> ints = Arrays.asList(222, 555, 666, 333, 111, 888, 777, 444);
        Queue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
        pq.addAll(ints);
        System.out.println("Priority Queue => " + pq);
        System.out.println("Max element in the list => " + pq.peek());
        System.out.println("......................");
        // another way
        Queue<Integer> pq1 = new PriorityQueue<>((a, b) -> b - a);
        pq1.addAll(ints);
        System.out.println("Priority Queue => " + pq1);
        System.out.println("Max element in the list => " + pq1.peek());
        /* OUTPUT
          Priority Queue => [888, 444, 777, 333, 111, 555, 666, 222]
          Max element in the list => 888
          ......................
           Priority Queue => [888, 444, 777, 333, 111, 555, 666, 222]
           Max element in the list => 888

         */


    }
}
public class KthLargestElement_1{
    public static void main(String[] args) {

        List<Integer> ints = Arrays.asList(222, 555, 666, 333, 111, 888, 777, 444);
        int k = 3;
        Queue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
        pq.addAll(ints);
        System.out.println("Priority Queue => " + pq);
        System.out.println("Max element in the list => " + pq.peek());
        while (--k > 0) {
            pq.poll();
        } // while
        System.out.println("Third largest => " + pq.peek());
/*
 Priority Queue => [888, 444, 777, 333, 111, 555, 666, 222]
Max element in the list => 888
Third largest => 666

 */
    }
}
public class KthLargestElement_2 {
    public static void main(String[] args) {
        List<Integer> ints = Arrays.asList(222, 555, 666, 333, 111, 888, 777, 444);
        int k = 3;

        Queue<Integer> pq1 = new PriorityQueue<>((a, b) -> b - a);
        pq1.addAll(ints);
        System.out.println("Priority Queue => " + pq1);
        System.out.println("Max element in the list => " + pq1.peek());
        while (--k > 0) {
            pq1.poll();
        } // while
        System.out.println("Third largest => " + pq1.peek());
        /*
          Priority Queue => [888, 444, 777, 333, 111, 555, 666, 222] 
          Max element in the list => 888 
          Third largest => 666

         */
    }
}
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(Collections.reverseOrder());
PriorityQueue<Integer> maxPQ = new PriorityQueue<>(Collections.reverseOrder()); 
PriorityQueue<Integer> maxPQ = new PriorityQueue<>((a,b) -> b - a); 
PriorityQueue<Integer> maxPQ = new PriorityQueue<>((a,b) -> b.compareTo(a)); 
import java.util.PriorityQueue;
import java.util.Comparator;
public class Main
{
    public static void main(String[] args) {
        PriorityQueue<Integer> nums = new PriorityQueue<>(new CustomComparator());
        nums.offer(21);
        nums.offer(1);
        nums.offer(8);
        nums.offer(2);
        nums.offer(-4);
        System.out.println(nums.peek());
    }
}
class CustomComparator implements Comparator<Integer>{
    @Override
    public int compare(Integer n1, Integer n2){
        int val = n1.compareTo(n2);
        if(val > 0)
           return -1;
        else if(val < 0)
            return 1;
        else
            return 0;
    }
}
PriorityQueue<> q = new PriorityQueue<Integer>(
                       (a,b) ->  -1 * Integer.compare(a, b)
                    );