Convert a queue to a list

What is the fastest way to convert Queue to List while maintaining the order of the queues?

+12
java list queue
source share
6 answers

The fastest way is to use LinkedList in the first place, which can be used as a list or queue.

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

Otherwise you need to take a copy

 List l = new ArrayList(q); 
+22
source share

Pass Queue To ArrayList Constructor

The easiest way is to simply create an ArrayList and pass Queue as an argument to the ArrayList constructor that accepts Collection . A Queue is a Collection , so it works.

This is the easiest way, and I believe that this is the fastest way.

 List<?> list = new ArrayList<>( myQueue ); 
+5
source share
 Queue queue = new LinkedList(); ... List list = new ArrayList(queue); 
+3
source share

Google:

 Queue fruitsQueue = new LinkedList(); fruitsQueue.add("Apples"); fruitsQueue.add("Bananas"); fruitsQueue.add("Oranges"); fruitsQueue.add("Grapes"); List fruitsList = new ArrayList(fruitsQueue); 
+1
source share

Answering an old question for users who are already in Java 8
Java 8 provides the ability to use threads, and you can get a list from the queue as:

For example:

 Queue<Student> queue = new LinkedList<>(); Student s1 = new Student("A",2); Student s2 = new Student("B",1); Student s3 = new Student("C",3); queue.add(s1); queue.add(s2); queue.add(s3); List<Student> studentList = queue.stream().collect(Collectors.toCollection(ArrayList::new)); 
0
source share

If you convert PriorityQueue to List, remember that this is actually a bunch, so the order is determined by the poll() method. The above methods will not preserve the natural order of the queue.

0
source share

All Articles