Conversion of a List to a Queue in Java
Last Updated :
25 Jan, 2024
In this article, We will learn about how to convert a List to a Queue in Java using various methods.
Prerequisite
Methods to Convert List to Queue in Java
In Java, there are a few ways to convert a List to a Queue. Here are some methods and ways you can achieve this:
- Use LinkedList Constructor
- Use ArrayDeque
- Use addAll method
1. LinkedList Constructor
Using LinkedList Constructor, seamlessly convert a List into a Queue by relying on the constructor of the LinkedList class.
Steps for Conversion
- Create a List.
- Use LinkedList Constructor to Create a Queue Interface and pass a created list as an argument.
- Access Queue Elements.
Syntax:
Queue<_type_> myQueue = new LinkedList<>(_ListName_);
Below is the example code for the above method:
Java
import java.util.*;
public class ListToQueueExample1 {
public static void main(String[] args) {
List<String> myList = Arrays.asList( "A" , "B" , "C" );
Queue<String> myQueue = new LinkedList<>(myList);
System.out.print( "Queue elements: " );
while (!myQueue.isEmpty()) {
System.out.print(myQueue.poll()+ ", " );
}
}
}
|
Output
Queue elements: A, B, C,
2. ArrayDeque
By employing the ArrayDeque constructor and passing the List as an argument, we can efficiently create a Queue with the same elements as the original List.
Steps for Conversion:
- Create a List.
- Use ArrayDeque Constructor to Create Queue Interface and pass created list as argument.
- Access Queue Elements.
Syntax:
Queue<_type_> myQueue = new ArrayDeque<>(_ListName_);
Below is the example code for the above method:
Java
import java.util.*;
public class ListToQueueExample2 {
public static void main(String[] args) {
List<String> myList = Arrays.asList( "A" , "B" , "C" );
Queue<String> myQueue = new ArrayDeque<>(myList);
System.out.print( "Queue elements: " );
while (!myQueue.isEmpty()) {
System.out.print(myQueue.poll()+ ", " );
}
}
}
|
Output
Queue elements: A, B, C,
3. addAll Method
The addAll Method is particularly useful when you already have a Queue instance and want to append elements from a List to it.
Steps for Conversion:
- Create a List.
- Create an Existing Queue(Empty)
- Use addAll Method with the List containing all elements.
Syntax:
MyQueue.addAll(_ListName_);
Below is the example code for the above method:
Java
import java.util.*;
public class ListToQueueExample3 {
public static void main(String[] args)
{
List<String> myList = List.of( "A" , "B" , "C" );
Queue<String> myQueue = new LinkedList<>();
myQueue.addAll(myList);
System.out.print( "Queue elements: " );
while (!myQueue.isEmpty()) {
System.out.print(myQueue.poll() + ", " );
}
}
}
|
Output
Queue elements: A, B, C,
Share your thoughts in the comments
Please Login to comment...