Convert a Queue to a List in Java

Java 8Object Oriented ProgrammingProgramming

In order to convert a Queue to a List in Java, we can create an LinkedList and pass the Queue as an argument in the parameterized constructor of an ArrayList. This can be done as follows −

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

The quickest way is used to LinkedList in the first place which can be used both as a List and a Queue. This can be done as follows −

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

Let us see a program to convert a queue to a list −

Example

 Live Demo

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class Example {
   public static void main(String[] args) {
      Queue q = new LinkedList();
      q.add("Good");
      q.add("Morning");
      List l = (List) q;
      System.out.println(l);
   }
}

Output

[Good, Morning]
raja
Published on 08-Jan-2019 12:26:48
Advertisements