Convert ArrayList to LinkedList in Java

In this post, we will see how to convert ArrayList to LinkedList in Java. The resultant LinkedList should contain all elements of the ArrayList.


 

We know that ArrayList is resizable-array implementation and LinkedList is Doubly-linked list implementation of the List interface.

ArrayList is usually faster than LinkedList as it offers constant-time positional access versus linear-time in a LinkedList. But LinkedList offers few constant-time operations such as adding elements to the beginning of the List or iterate over the List to delete elements from its interior, as opposed to linear-time in an ArrayList.

 
Below are few ways to convert ArrayList to LinkedList in Java –

 

1. Naive Solution

Naive solution would be to create an empty LinkedList instance and add all elements present in the ArrayList to it one by one.

 

Download   Run Code

Output:

[RED, BLUE, GREEN]

 

2. Plain Java

To construct a new LinkedList from ArrayList, we can either pass ArrayList object to LinkedList constructor or to addAll() method.

 

3. Java 8

The idea is to convert ArrayList to a Stream and collect elements of a stream in a LinkedList using Stream.collect() method which accepts a collector.

We can use collector returned by Collectors.toCollection() method that can accept desired constructor reference LinkedList::new.

 

 

4. Google’s Guava library

Guava also provides LinkedList implementation which can be used to create an empty LinkedList instance.

 

5. Conversion between incompatible types

 
If ArrayList and LinkedList is expected to have incompatible types, we’ll need to convert them manually:

We can do better in Java 8 as illustrated below:

or even better,

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz