I am trying to understand the following line which initiates a Priority Queue:
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> b[1] - a[1]);
Comparing with Constructor section in the document, https://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html
I couldn't figure out which Constructor it uses. Could someone please share the thought?
Also, is there a document that could better explain/define syntax (a, b) -> b[1] - a[1]
... though I could guess what it means.
Thanks a lot!
A priority queue in Java is a special type of queue wherein all the elements are ordered as per their natural ordering or based on a custom Comparator supplied at the time of creation.
Priority queue can be initialized in two ways either by pushing all elements one by one or by initializing using their constructor. In this article, we will discuss both methods and examine their time complexities.
Q #4) Is Java Priority queue max or min? Answer: By default, the priority queue in Java is min Priority queue with natural ordering. To make it max, we have to use a custom comparator so that head of the queue returns the greatest element in the queue.
Your construction of the PriorityQueue
uses a constructor that didn't yet exist in 1.7, which is the version of the Javadocs you linked.
It uses a constructor that takes a Comparator
that was added for Java 1.8, which is matched to the lambda expression you supplied.
Creates a
PriorityQueue
with the default initial capacity and whose elements are ordered according to the specified comparator.Since:
1.8
Lambda expressions were introduced with Java 1.8. Here, basically you have 2 arguments and expression that are matched to a functional interface --Comparator
.
Since Java 8, there's a new constructor that has a Comparator
for argument:
public PriorityQueue(Comparator<? super E> comparator)
Thus the initialization using a lambda is valid Java 8+ code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With