6
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?

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
KJW
  • 15,035
  • 47
  • 137
  • 243

2 Answers2

12

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
azerafati
  • 18,215
  • 7
  • 67
  • 72
8

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.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 1
    isn't this slower than addAll() ? – KJW Oct 30 '11 at 08:22
  • 1
    yes but I want to retain the order of the Collection and simply place this entire Collection infront of other elements in the queue. – KJW Oct 30 '11 at 08:30
  • 2
    that's why you should iterate in reverse order, so that it ends up in the initial order – Bozho Oct 30 '11 at 08:32