Search code examples
javapriority-queue

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!


Solution

  • 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.