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

10.5k views Asked by At
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?

2

There are 2 answers

3
Bozho On BEST ANSWER

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.

1
azerafati On

Actually I was looking for the same thing, and this worked for me!!

samplelist.addAll(0,items); // 0 is the index where items are added on the list