Saturday, 16 August 2014

Array To List and List to Array

Following code snippet contains some different way to convert array into List and List into array.



package coreCollection;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ArraytoList {

/**
* @param args
*/
public static void main(String[] args) {

String [] arr={"one","tow","three","four","five"};

/* Array To List. */

//first Way
List<String> ll=Arrays.asList(arr);
System.out.println(ll);

//Second Way
List<String> list=new ArrayList<String>();
for(String s:arr){
list.add(s);
}
System.out.println(list);

/* List To Array */

//First way.
String []strArr=(String[]) ll.toArray();
printMe(strArr);

   //Second way.
String [] stArr=new String[ll.size()];
for(int i=0;i<ll.size();i++){
stArr[i]=ll.get(i);
}
printMe(stArr);

}

/* generic method. */
private static <T> void printMe(T [] arr){
for(T s:arr){
         System.out.print(s+", ");
}
System.out.println();
}

}


Output:


No comments:

Post a Comment