Skip to content

Iteration order over a Queue in collections #82

@PhilippeFerreiraDeSousa

Description

@PhilippeFerreiraDeSousa

The iteration order of a queue is the opposite of the conventional sense. Technically the theoretical definition of a queue does not impose anything or whether you should be able to iterate over a queue, but this is counter intuitive to iterate in the opposite order than popping. Queues are FIFO and it makes sense to iterate in the same order: If you add 1 then 2 then 3 to the queue, iterating should give you 1 then 2 then 3 (and leave all 3 elements in the queue of course).
I checked in python (deque from collections) and java (java.util.LinkedList implementation of java.util.Queue) and they do what I was expecting.

Stanza:

$ jstanza repl
stanza> val q = Queue<Int>()
stanza> add(q, 1)
stanza> add(q, 2)
stanza> add(q, 3)
stanza> println(to-tuple $ q)
[3 2 1]

Python:

lbstanza$ python3.8
Python 3.8.0 (default, Feb 25 2021, 22:10:10) 
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import deque
>>> d = deque()
>>> d.append(1)
>>> d.append(2)
>>> d.append(3)
>>> d
deque([1, 2, 3])
>>> list(d)
[1, 2, 3]

Java:

import java.util.LinkedList;
import java.util.Queue;

class Main
{
	// Iterate through Queue in Java
	public static void main(String[] args)
	{
		Queue<Integer> queue = new LinkedList<Integer>();
		queue.add(1);
		queue.add(2);
		queue.add(3);

		for (Integer item: queue) {
			System.out.println(item);
		}
	}
}

gives

1
2
3

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions