![]() |
VOOZH | about |
Given an array list, your task is to write a program to convert the given array list to Linked List in Java.
Examples:
Input: ArrayList: [Geeks, forGeeks, A computer Portal] Output: LinkedList: [Geeks, forGeeks, A computer Portal] Input: ArrayList: [1, 2, 3, 4, 5] Output: LinkedList: [1, 2, 3, 4, 5]
ArrayList - An ArrayList is a part of the collection framework and is present in java.util package. It provides us dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed.
Linked List - A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers as shown in the below image:
There are numerous approaches to convert the given array list to a linked list in Java. A few of them are listed below.
In this method, an empty LinkedList is created and all elements present of the ArrayList are added to it one by one.
Algorithm:
Code:
ArrayList: [Geeks, forGeeks, A computer Portal] LinkedList: [Geeks, forGeeks, A computer Portal]
In this method, the ArrayList is passed as the parameter into the LinkedList constructor.
Algorithm:
Code:
ArrayList: [Geeks, forGeeks, A computer Portal] LinkedList: [Geeks, forGeeks, A computer Portal]
This method includes converting the ArrayList to a Stream and collect elements of a stream in a LinkedList using Stream.collect() method which accepts a collector.
Algorithm:
Code:
ArrayList: [Geeks, forGeeks, A computer Portal] LinkedList: [Geeks, forGeeks, A computer Portal]
Guava also provides a LinkedList implementation which can be used to create a LinkedList from another collection using Collection.addAll() method.
Algorithm:
Code:
ArrayList: [Geeks, forGeeks, A computer Portal] LinkedList: [Geeks, forGeeks, A computer Portal]
This method can be used if the required TreeMap is of the different type than the HashMap. In this, the conversion needs to be done manually.
Algorithm:
Code:
ArrayList: [1, 2, 3, 4, 5] LinkedList: [1, 2, 3, 4, 5]