Home > Blockchain >  Retrieve all queue data in for loop
Retrieve all queue data in for loop

Time:08-31

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

CodePudding user response:

The problem is that each time you remove an item, the queue gets smaller, so you stop early. At start the size is 3, after the first iteration, the size is 2, at the third iteration the size is 1, and 2 <= 1 is false, so the third item is not processed.

Use Queue.poll() instead to get and remove the item from the queue. poll() returns null when the queue is empty.

String value;
while ((value = queue.poll()) != null) {
    int queueBatchNumber =  Integer.valueOf(value);
    // rest of your code
}

CodePudding user response:

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.

CodePudding user response:

If you want to go through all elements of a collection while clearing it, you probably want to use Iterator which has a remove method.

Iterator<Integer> iterator = q.iterator();
while (iterator.hasNext()) {
  doStuffWith(iterator.next());
  iterator.remove();
}

Also note that your for loop is wrong to begin with. If you do need to iterator through an ordered collection (like a List), you want to stop short of its actual size():

for (int i = 0; i < list.size(); i  ) { // i < list.size(), not i <= list.size()
  • Related