Convert an Array to a Collection object using Java

Hi All,

This article will shows how to convert an array of strings to a List collection object.
To convert the array we have to use Arrays class’s static method  asList in which we will pass the staring array object.

To print the result  simply use iterator to traverse through the collection.

import java.util.List;
import java.util.Arrays;
import java.util.Iterator;
public class TestStringToArray {
public static void main(String[] args) {

//declare the string array
String[] strArray = {“Value 1”, “Value 2”, “VALUE 3”};

//Create a List Object and invoke asList method to convert
List listObject = Arrays.asList(strArray);

//Print the collection object
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}

}
}


Thanks
R Vashi

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.