Search code examples
javacollectionsarraydeque

java: how to addAll(Collection<>) to the front of the queue?


public void traverse(Node root){
    ArrayDeque<Node> queue = new ArrayDeque<Node>();
        queue.add(root);

    while(!queue.isEmpty()){
        Node currentNode = queue.pollFirst();   
        List<Node> nl = getChildrenfromDB(currentNode);
        queue.addAll(nl);
    }

how would I get addAll(nl) to add the entire collection(List<Node>) to the front of the queue?


Solution

  • There is nothing built-in. But it is simple to emulate - just iterate the list in reverse order and add the elements. That way they will end up in the queue in the right order.

    for (int i = list.size() - 1; i >=0; i--) {
        queue.addFirst(node);
    }
    

    Other ways to iterate backwards are:

    • LinkedList's descending iterator
    • Collections.reverse(..)

    Pick one which fits your case.