This example shows how to convert an array to the LinkedList in Java. The example also shows how to convert array to a linked list using asList and addAll methods.
How to convert an array to LinkedList in Java?
There are a couple of ways using which we can convert an array to a LinkedList object in Java.
1. Using the asList method
The LinkedList class does not provide any direct method to convert an array to the linked list. So we will first convert an array to the list and then create a linked list object from that list.
The asList
method of the Arrays class converts an array to the list.
1 |
public static <T> List<T> asList(T... a) |
The List object returned by this method is backed by the original array. Once we get the List from the array, we will create a linked list by using this array as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import java.util.Arrays; import java.util.LinkedList; import java.util.List; public class ArrayToLinkedListExample { public static void main(String[] args) { String[] strColors = {"Red", "Green", "Blue"}; //convert array to list List<String> listColors = Arrays.asList(strColors); /* * Create LinkedList from the List using the * constructor */ LinkedList<String> linkedListColors = new LinkedList<String>( listColors ); //print LinkedList for(String str : linkedListColors){ System.out.println( str ); } } } |
Output
1 2 3 |
Red Green Blue |
2. Using the addAll method
In this approach, we will first create an empty LinkedList object and then add all the elements of an array to the LinkedList object using the addAll
method of the Collections class.
1 2 3 4 5 6 7 8 9 10 11 12 |
String[] strColors = {"Red", "Green", "Blue"}; //create new empty linked list LinkedList<String> linkedListColors = new LinkedList<String>(); //add all elements of an array to linked list Collections.addAll(linkedListColors, strColors); //print LinkedList for(String str : linkedListColors){ System.out.println( str ); } |
Output
1 2 3 |
Red Green Blue |
This approach is a preferred way to convert an array to a linked list object since it does not involve an additional step of converting to a list from an array.
This example is a part of the LinkedList in Java tutorial.
Please let me know your views in the comments section below.
References:
Java 8 LinkedList