[英]Java Lambdas: Comparator with PriorityQueue
考慮一個優先隊列
PriorityQueue<Integer> heap = new PriorityQueue<Integer>();
我可以在這里以兩種方式定義比較器,一種是使用lambda
,另一種是使用Comparator()
類
假設這兩種方式對 2 個變量進行簡單的整數比較,我想知道哪個變量是我們要比較的值,哪個變量包含隊列中的現有值
例如:
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;
}
});
當我調用heap.add(2)
后跟一個heap.add(3)
,第二個add()
調用會觸發compare(a,b)
函數並打印a=3 & b=2
這意味着這里a
有新值, b
是隊列中的現有值
同樣,你能告訴我下面的 lambda 表達式是否會類似地工作還是相反?
PriorityQueue<Integer> heap = new PriorityQueue<Integer>((a,b) -> b-a);
我知道這個問題可以用更簡單的方式寫出來,但我現在無法做到。
此外,這兩個打印相同的值,即降序 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());
}
您定義Comparator
兩種方法是等效的。 你的 lambda 版本在編譯后實際上會擴展到另一個版本,因為Comparator
是一個函數式接口。
這是定義Comparator
的第三種更短的方法,在Comparator
接口上使用靜態工廠方法:
PriorityQueue<Integer> heap3 = new PriorityQueue<>(Comparator.reverseOrder());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.