Skip to content
Advertisement

Retrieve all queue data in for loop

I have the following code which works fine but I am struggling to figure out how to retrieve the last value in the queue.

Queue<String> q = bi.getStringQueue();

System.out.println("QUEUE SIZE : "+q.size());

for(int x =0; x <= q.size(); x++){
    int queueBatchNumber =  Integer.valueOf(q.peek());

    System.out.println("Attempting auto post on AR batch "+queueBatchNumber);

    setReadyToPostAR(queueBatchNumber);
    autoPostAR(queueBatchNumber);

    System.out.println("Auto post on AR batch "+queueBatchNumber + " complete");

    q.remove();
}

Here is the output:

QUEUE SIZE : 3 
Attempting auto post on AR batch 462212
Auto post on AR batch 462212 complete
Attempting auto post on AR batch 462213
Auto post on AR batch 462213 complete

Advertisement

Answer

Since you’re incrementing x and decreasing the size of the queue, x will eventually become bigger than the remaining queue size before the queue is empty.

You can change your loop to while (!queue.isEmpty()) instead.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement