Given a Vector, the task is to Convert Vector to List in Java
Examples:
Input: Vector: [1, 2, 3, 4, 5]
Output: List: [1, 2, 3, 4, 5]
Input : Vector = [a, b, c, d, e, f]
Output : List = [a, b, c, d, e, f]
- Using Collections.list() method
Syntax:
List list = Collections.list(vec.elements());
Approach:
- Get the Vector
- Convert into list using Collections.list(vector.elements()) method, which returns a List of objects.
- Print the List
Below is the implementation of the above approach:
import java.util.*;
public class GFG {
public static void main(String[] args)
{
Vector<String> vec = new Vector<String>();
vec.add( "1" );
vec.add( "2" );
vec.add( "3" );
vec.add( "4" );
vec.add( "5" );
System.out.println( "Vector: " + vec);
List<String>
list = Collections.list(vec.elements());
System.out.println( "List:" + list);
}
}
|
Output:
Vector: [1, 2, 3, 4, 5]
List:[1, 2, 3, 4, 5]
- Using Collection.unmodifiableList()
Syntax:
List list = Collections.unmodifiableList(vector);
Approach:
- Get the Vector
- Convert into list using Collections.unmodifiableList(vector) method, which returns an immutable List of objects.
- Print the List
Below is the implementation of the above approach:
import java.util.*;
public class GFG {
public static void main(String[] args)
{
Vector<String> vec = new Vector<String>();
vec.add( "1" );
vec.add( "2" );
vec.add( "3" );
vec.add( "4" );
vec.add( "5" );
System.out.println( "Vector: " + vec);
List<String>
list = Collections.unmodifiableList(vec);
System.out.println( "List:" + list);
}
}
|
Output:
Vector: [1, 2, 3, 4, 5]
List:[1, 2, 3, 4, 5]
- Using constructor
Syntax:
List list = new ArrayList(vector);
Approach:
- Get the Vector
- Create a List from the Vector by passing the vector as the parameter.
- Print the List
Below is the implementation of the above approach:
import java.util.*;
public class GFG {
public static void main(String[] args)
{
Vector<String> vec = new Vector<String>();
vec.add( "1" );
vec.add( "2" );
vec.add( "3" );
vec.add( "4" );
vec.add( "5" );
System.out.println( "Vector: " + vec);
List<String>
list = new ArrayList<String>(vec);
System.out.println( "List:" + list);
}
}
|
Output:
Vector: [1, 2, 3, 4, 5]
List:[1, 2, 3, 4, 5]
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
11 Dec, 2018
Like Article
Save Article