Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a Queue to List

Tags:

What is the fastest way to convert a Queue into a List while keeping the Queue order?

like image 388
MBZ Avatar asked Oct 08 '12 10:10

MBZ


2 Answers

The fastest is to use a LinkedList in the first place which can be used as a List or a Queue.

Queue q = new LinkedList(); List l = (List) q; 

Otherwise you need to take a copy

List l = new ArrayList(q); 

Note: When dealing with PriorityQueue, Use a loop, poll each element and add to list. PriorityQueue to List not maintaining the heap order.

like image 102
Peter Lawrey Avatar answered Nov 19 '22 11:11

Peter Lawrey


Pass Queue To ArrayList Constructor

The easiest way to just create a ArrayList and pass your Queue as an argument in the constructor of ArrayList that takes a Collection. A Queue is a Collection, so that works.

This is the easiest way and I believe fastest way too.

List<?> list = new ArrayList<>( myQueue ); 
like image 28
2 revs, 2 users 75% Avatar answered Nov 19 '22 11:11

2 revs, 2 users 75%