[英]Java Lambdas: Comparator with PriorityQueue
Consider a priority queue考虑一个优先队列
PriorityQueue<Integer> heap = new PriorityQueue<Integer>();
I can define a comparator in two ways here, one by using lambda
and the other using the Comparator()
class我可以在这里以两种方式定义比较器,一种是使用lambda
,另一种是使用Comparator()
类
Assuming a simple integer comparison of 2 variables for both these ways, I would like to know which variable is the value we want to compare and which variable contains the existing value from the queue假设这两种方式对 2 个变量进行简单的整数比较,我想知道哪个变量是我们要比较的值,哪个变量包含队列中的现有值
For exammple:例如:
PriorityQueue<Integer> heap = new PriorityQueue<Integer>(new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
System.out.println(a+" "+b);
return b-a;
}
});
When I call heap.add(2)
followed by a heap.add(3)
, the second add()
call triggers the compare(a,b)
function and prints a=3 & b=2
which means that here, a
has the new value and b
is the existing value from the queue当我调用heap.add(2)
后跟一个heap.add(3)
,第二个add()
调用会触发compare(a,b)
函数并打印a=3 & b=2
这意味着这里a
有新值, b
是队列中的现有值
Similarly, can you tell me if the below lambda expression will work similarly or is it the other way around ?同样,你能告诉我下面的 lambda 表达式是否会类似地工作还是相反?
PriorityQueue<Integer> heap = new PriorityQueue<Integer>((a,b) -> b-a);
I know the question could have been written in much simpler manner but I just couldn't manage to do it at the moment.我知道这个问题可以用更简单的方式写出来,但我现在无法做到。
Addtionally, these two print the same values ie decreasing order 4,3,2,1此外,这两个打印相同的值,即降序 4,3,2,1
PriorityQueue<Integer> heap2 = new PriorityQueue<Integer>(new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
// System.out.println(a+" "+b);
return b-a;
}
});
PriorityQueue<Integer> heap = new PriorityQueue<Integer>(
(a,b) -> b-a
);
heap.add(1);
heap.add(2);
heap.add(3);
heap.add(4);
heap2.add(1);
heap2.add(2);
heap2.add(3);
heap2.add(4);
while (!heap.isEmpty()) {
System.out.println(heap.poll()+" "+heap2.poll());
}
Your two ways to define the Comparator
are equivalent.您定义Comparator
两种方法是等效的。 Your lambda version actually expands to the other version after compiling, because Comparator
is a functional interface.你的 lambda 版本在编译后实际上会扩展到另一个版本,因为Comparator
是一个函数式接口。
Here's a third shorter way to define your Comparator
, using a static factory method on the Comparator
interface:这是定义Comparator
的第三种更短的方法,在Comparator
接口上使用静态工厂方法:
PriorityQueue<Integer> heap3 = new PriorityQueue<>(Comparator.reverseOrder());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.