Thursday, August 06, 2009

Converting an Array to a List

Java Collections API has very useful methods to play with all the data structures. Conversion between the collections made so easy.

following line of code converts an array into a list.
List list = Arrays.asList(str); // str is an array

Following program converts an array of strings into a List.

package com.blog.javaexposure.util;

import java.util.Arrays;
import java.util.List;

public class Array2List {

public static void main(String rags[]){
// Creating a string array
String[] str = {"One","Two","Three","Four","Five"};

// Convert array to List
List list = Arrays.asList(str);

System.out.println("Elements in the list are:");
//Checking the elements in the list
for(String s : list){
System.out.println(s);
}
}
}

No comments:

Post a Comment

È