I am trying to use a priority queue with a custom comparator, However I am not able to achieve my expected functionality.:
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
public class TestMain {
public static void main(String[] args) {
Queue<Node> queue = new PriorityQueue<>(new Comparator<Node>() {
public int compare(Node a, Node b) {
if(a.level == b.level) {
return a.data - b.data;
}
return a.level - b.level;
}
});
queue.add(new Node(0,1));
queue.add(new Node(1,2));
queue.add(new Node(1,4));
queue.add(new Node(2,3));
queue.add(new Node(2,7));
queue.add(new Node(2,2));
queue.add(new Node(2,5));
System.out.println(queue);
}
private static class Node {
int level;
int data;
Node(int level, int data) {
this.level = level;
this.data = data;
}
public String toString() {
return level + ":" + data;
}
}
}
Expected output = [0:1, 1:2, 1:4, 2:2, 2:3, 2:5, 2:7]
Actual output = [0:1, 1:2, 1:4, 2:3, 2:7, 2:2, 2:5]
I want the elements in the priority queue to be ordered by the level first then by data.
new PriorityQueue<>(Comparator.comparingInt(Node::getLevel).thenComparing(Node::getData))