i want to get out elements from a queue in order in which they inserted in the queue
for example Basic functioning of Queue as—
add(10);
add(100);
add(25);
add(78);
add(50);
whenever i poll() elements from queue they must be in same order in which they were inserted 10, 100 , 25, 78, 50
Have a look at what i tried
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
class NewClass {
public static void main(String[] args) {
Queue<Integer> q1 = new PriorityQueue<>();
Queue<Integer> q2 = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if (o1 <= o2) {
return 1;
} else {
return -1;
}
}
});
Queue q = new PriorityQueue(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return 1;
}
});
Random r = new Random();
for (int i = 0; i < 10; i++) {
int no = r.nextInt(20);
System.out.print(no + " ");
q.add(no);
q1.add(no);
q2.add(no);
}
System.out.println();
System.out.println("poll from queue in default sorting oredr");
while (!q1.isEmpty()) {
System.out.print(q1.poll() + " ");
}
System.out.println();
System.out.println("poll from queue in descending oredr");
while (!q2.isEmpty()) {
System.out.print(q2.poll() + " ");
}
System.out.println("");
System.out.println("poll from queue in oreder in which we insert in queue");
while (!q.isEmpty()) {
System.out.print(q.poll() + " ");
}
}
}
Below is what output i got:–
![alt text][1]
It worked for Default Sorting Order and for descending Order but dont know why it is not working for basic Queue functioning as poll() in same order in which it was inserted
My Main concern here is use priorityQueue predefine functions to implement above… i did it using arrayList, LinkedList already…
other suggestion will also be appriciated
Thanks in Advance
[1]: https://discuss.codechef.com/upfiles/Capture_esnCNGN.PNG