Are you looking for the best way to convert LinkedList to ArrayList? You are at the right place! Here we are going to share some of the best ways to convert LinkedList to ArrayList in Java.
Method 1:
You can easily convert LinkedList to ArrayList by initializing ArrayList by passing the LinkedList object in Parameter of the ArrayList’s constructor.
Source code:
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class LinkedListToArrayList {
public static void main(String[] args) {
LinkedList namesList = new LinkedList<>();
namesList.add("Sam");
namesList.add("Ali");
namesList.add("Lara");
namesList.add("Sara");
//Printing LinkedList
System.out.println("Linked list: "+namesList);
List arrayList = new ArrayList<>(namesList);
//Printing converted list
System.out.println("Converted List/ArrayList: " + arrayList);
}
}
Output:
run:
Linked list: [Sam, Ali, Lara, Sara]
Converted ArrayList: [Sam, Ali, Lara, Sara]
BUILD SUCCESSFUL (total time: 0 seconds)
Method 2:
You can simply copy the elements of the LinkedList to the ArrayList. Check the sample code given below to understand the logic of method 2.
Source code:
import java.util.ArrayList;
import java.util.LinkedList;
public class LinkedListToArrayList {
public static ArrayList ConvertLinkedListToArrayList(LinkedList linkedList) {
ArrayList arrayList = new ArrayList<>();
for(int i=0; i<linkedList.size(); i++){
arrayList.add(linkedList.get(i));
}
return arrayList;
}
public static void main(String[] args) {
LinkedList namesList = new LinkedList<>();
namesList.add("Sam");
namesList.add("Ali");
namesList.add("Lara");
namesList.add("Sara");
System.out.println("Linked list: "+namesList);
ArrayList arrayList= ConvertLinkedListToArrayList(namesList);
//Printing converted list
System.out.println("Converted List/ArrayList: " + arrayList);
}
}
Output:
run:
Linked list: [Sam, Ali, Lara, Sara]
Converted ArrayList: [Sam, Ali, Lara, Sara]
BUILD SUCCESSFUL (total time: 0 seconds)
References:
Happy Learning 🙂