- A constructor call to
PriorityQueue accepts a Comparator.
new PriorityQueue<>((a,b) -> map.get(b) - map.get(a));
Comparator is defined as a FunctionalInterface.
This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.
- The abstract method of the functional interface is,
int compare(T o1, T o2)
...where T is the type within the queue, in this case, Integer. In other words, the method requires two arguments of the same type as input and produces an int as output (note: this is the same general method shape as a BiFunction or ToIntBiFunction).
- The lambda expression provided is,
(a,b) -> map.get(b) - map.get(a)
...which satisfies the abstract method signature as,
(Integer a, Integer b) -> map.get(b) - map.get(a)
...by looking up the (Integer) values corresponding to both a and b in the previously-instantiated HashMap and subtracting one Integer from the other to return an int. Subtraction results in the higher value being "prioritized".
- This implementation assumes every
Integer added to the queue has already been added as a key in the map, with a corresponding, non-null value; otherwise, the Comparator throws a NullPointerException.
b - agives you a negative value ifais greater and a positive value ifbis greater, except when it doesn't. You could replace the lambda withComparator.comparing(map::get).b - acomparator is a bug.-100and100(for reasons we don't know, e.g. plotting); or some developer copy & paste that code for a different use case