In this article, we will write a Java program to convert Vector to List, Vector and list both data structures used for storing elements, but their performance for various operations differ in different scenarios. More on this at Vector vs List.
You may also want to checkout other conversion articles such as Vector to ArrayList and Vector to Array conversion.
Java Program to convert Vector to List
In this example, we have a vector of string type. We are converting it into a List using Collections.list()
method.
import java.util.Vector; import java.util.List; import java.util.Collections; public class VectorToList { public static void main(String[] args) { // Step1: Creating a Vector of String elements Vector<String> vector = new Vector<String>(); // Step2: Populating Vector vector.add("Tim"); vector.add("Rock"); vector.add("Hulk"); vector.add("Rick"); vector.add("James"); // Step3: Displaying Vector elements System.out.println("Vector Elements :"); for (String str : vector){ System.out.println(str); } // Step4: Converting Vector to List List<String> list = Collections.list(vector.elements()); // Step 5: Displaying List Elements System.out.println("\nList Elements :"); for (String str2 : list){ System.out.println(str2); } } }
Output:
Vector Elements :
Tim
Rock
Hulk
Rick
James
List Elements :
Tim
Rock
Hulk
Rick
James
As you can see both Vector and List are having same elements after conversion, Thus we can conclude that this conversion was successful.
Leave a Reply