Java Priority Queue with a custom anonymous comparator

This question was answered a while ago and I want to give some new options that are available.

1) Using lambda in case if your Node class doesn't implement Comparator interface and you don't want (or can't) add it:

  new PriorityQueue<>((node1, node2) -> Integer.compare(node1.getCost(), node2.getCost()));

2) Simple reverse order approach (require Node to implement Comparator interface):

  new PriorityQueue<>(Comparator.reverseOrder());

3) Using utility function:

  new PriorityQueue<>(NodeUtil::customCompare);

  public static int customCompare(Node n1, Node n2) {
       return Integer.compare(n1.getCost(), n2.getCost());
  }

Absolutely.

You can use a PriorityQueue based on an anonymous Comparator passed to the constructor:

int initCapacity = 10;
PriorityQueue<Node> pq = new PriorityQueue<Node>(initCapacity, new Comparator<Node>() {
    public int compare(Node n1, Node n2) {
        // compare n1 and n2
    }
});
// use pq as you would use any PriorityQueue

If your Node class already implements Comparable you don't even need to define a new Comparator, as that order will be used by default. Barring any other method, the natural ordering between objects will be used.


From the Javadocs:

An unbounded priority queue based on a priority heap. This queue orders elements according to an order specified at construction time, which is specified either according to their natural order (see Comparable), or according to a Comparator

Furthermore, PriorityQueues support generic data types. Therefore, if you implement Comparable in your Node class, then you can create a PriorityQueue<Node> and use it normally.

Alternately, there is a constructor PriorityQueue(int initialCapacity, Comparator<? super E> comparator) that takes in a Comparator as part of the PriorityQueue constructor. If you prefer this method, your node class does not need to contain the extra code needed when inheriting Comparable.


public class Node implements Comparable<Node>{

    public int compareTo(Node o) {
         // your comparative function
         return 0;
    }

}

if compareTo returns a negative int, it means "less than", 0 means "equals", 1 means "greater than"

that one function is all you need to be able to use PriorityQueue.

EDIT: comparison is other way, i messed that up. -1 < | 0 = | 1 > i alreays read those right to left for some reason.