This is an implementation that shows you how to override the comparator to sort objects by a property in a Priority Queue. You can use Priority Queues in algorithms like Dijkstra’s and A* to remove the element with the least f(n) value in each iteration. Overriding the compare method can be used to sort ArrayLists (Dynamic Arrays in Java) with sort() method.
Comparator
package algos; import java.util.Comparator; import java.util.PriorityQueue; class StringLengthComparator implements Comparator { @Override public int compare(Node x, Node y) { // Real code should // probably be more robust // You could also just return x.val- y.val, // which would be more efficient. if (x.val < y.val) { return -1; } if (x.val > y.val) { return 1; } return 0; } } class Node { String name; int val; public Node(String name, int val) { this.name = name; this.val = val; } } public class pqcls { public static void main(String[] args) { Comparator comparator = new StringLengthComparator(); PriorityQueue queue = new PriorityQueue(10, comparator); Node n1 = new Node("Shiva", 2); Node n2 = new Node("John", 1); queue.add(n1); queue.add(n2); while (queue.size() != 0) { System.out.println(queue.remove().name); } } }
Output:
John
Shiva
Lambda Functions
If you want to use a more shorter format you can use lambda functions
package algos; import java.util.PriorityQueue; public class pqcls { public static void main(String[] args) { PriorityQueue<Node> queue = new PriorityQueue<Node>(10, (a,b)->a.val-b.val); Node n1 = new Node("Shiva", 2); Node n2 = new Node("John", 1); queue.add(n1); queue.add(n2); while (queue.size() != 0) { System.out.println(queue.remove().name); } } }
Output:
John
Shiva