简体   繁体   English

Java 中的比较器和 PriorityQueue 是如何工作的?

[英]How comparator and PriorityQueue in Java works?

This is the code i used to reverse the normal working of priorityQueue in Java.这是我用来扭转Java中priorityQueue正常工作的代码。 But i don't understand what is done by the lambda function i have put inside the parantheses.但我不明白我放在括号内的 lambda function 做了什么。 Can somedy explain that.有人可以解释一下。

PriorityQueue pq = new PriorityQueue<>( (a,b) -> b - a ); PriorityQueue pq = new PriorityQueue<>( (a,b) -> b - a );

import java.util.*;
public class Main
{
    public static void main(String[] args) {
        PriorityQueue<Integer> pq = new PriorityQueue<>((a,b) -> b - a);
        
        pq.add(2);
        pq.add(4);
        pq.add(1);
        pq.add(100);
        
        System.out.println(pq);
        System.out.println(pq.remove());
        System.out.println(pq.remove());
        System.out.println(pq.remove());
        System.out.println(pq.remove());
        
    }
} 

The comparison function is a function that must return any value less than 0 when the first parameter should be ordered before the second, any value greater than 0 when the second parameter should be ordered before the first and 0 if the two are equivalent for ordering.比较 function 是一个 function ,当第一个参数应该在第二个之前排序时,必须返回任何小于0的值,当第二个参数应该在第一个之前排序时,任何大于0的值都必须返回,如果两者对于排序等价,则返回0

It is used in within the PriorityQueue internally to determine relative ordering of elements by comparing its result with 0.它在内部的PriorityQueue中使用,通过将其结果与 0 进行比较来确定元素的相对顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM