Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: PriorityQueue initializations

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!

like image 618
Edamame Avatar asked Jan 31 '18 23:01

Edamame


People also ask

What is PriorityQueue in Java?

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.

How do I initialize PriorityQueue?

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.

Is Java PriorityQueue Min or Max?

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.


2 Answers

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.

like image 158
rgettman Avatar answered Oct 03 '22 11:10

rgettman


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.

like image 26
Luiggi Mendoza Avatar answered Oct 03 '22 10:10

Luiggi Mendoza