5

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!

3
  • 2
    It looks like a Comparator is being supplied to the queue so that items are added in the correct order. The Java 8 PriorityQueue implementation allows that form of the constructor. Commented Jan 31, 2018 at 23:47
  • 1
    You are looking in the wrong version of javadoc. It's obviously a creature from Java 8. Commented Jan 31, 2018 at 23:48
  • 2
    Whenever you see a lambda ->, it requires at least Java 1.8 to compile! Commented Jan 31, 2018 at 23:49

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

1

In Priority Queue you will essentially put user define objects, so to do it priority queue asks you how to order these objects (because priority queues are like heap data structures -- a min/max heap ) so we give it a Comparator which has a compare method ideally denoted by ((a, b) -> b[1] - a[1]) , this method give +ve, -ve or a zero result based on b > a , b < a or b = a. By this result it decides whether it should arrange the elements in ascending or descending order.

https://github.com/openjdk-mirror/jdk7u-jdk/blob/master/src/share/classes/java/util/PriorityQueue.java

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.