Use stream API to convert ArrayList to LinkedList
If you are using Java 8 or higher version, we can use Java Stream API
to convert ArrayList
to LinkedList
. We can use the stream()
method to get a stream of elements from the ArrayList
and collect()
method to collect the elements into a LinkedList
.
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("Mango");
arrayList.add("Apple");
arrayList.add("Orange");
System.out.println("ArrayList: ");
System.out.println(arrayList);
// ArrayList to LinkedList using Java Stream API
System.out.println("LinkedList: ");
LinkedList<String> linkedList = arrayList.stream()
.collect(Collectors.toCollection(LinkedList::new));
System.out.println(linkedList);
}
}
To run the code, open your terminal and navigate to the directory containing your java file. Then, compile and run the code using the following command:
javac Main.java && java Main
You should see the output:
ArrayList:
[Mango, Apple, Orange]
LinkedList:
[Mango, Apple, Orange]