Convert Java Array To List

This article will show you how to convert Java Array to List. There are two method in below java code. One method convert a Java String Array to String List, the other convert Java Object Array to Object List.

public class JavaArrayToListConverter {

	public static void main(String[] args) {

		/* Declare and initiate a String array. */
		String strArr[] = {"TestNG", "Selenium", "WebDriver", "Hibernate", "Spring"};
		
		JavaArrayToListConverter.stringArrayToList(strArr);
		
		JavaArrayToListConverter.objArrayToList(strArr);
		
	}
	/* Convert a String array to an editable list. */
	private static List<String> stringArrayToList(String strArr[])
	{
		/* Declare return object. */
		List<String> retObj = new ArrayList<String>();
		if(strArr!=null)
		{
			/* This method will covert the array to a not editable list which can not add or delete item because the list's length is fixed. */
			retObj = Arrays.asList(strArr);
			/* So below method will throw a java.lang.UnsupportedOperationException exception. 
			retObj.add("Hadoop");*/
			
			/* Create a new editable list. */
			List<String> retList = new ArrayList<String>();
			/* Add all items in retObj (not editable) to retList (editable).*/
			retList.addAll(retObj);
			/* Point retObj to the retList. */
			retObj = retList;
			/* Now can add element in retObj. */
			retObj.add("Hadoop");
			/* Add element at specified index. */
			retObj.add(2, "Sql Server");
			
			/* Loop in retObj.*/
			int size = retObj.size();
			for(int i=0;i<size;i++)
			{
				String str = retObj.get(i);
				/* Print out each item. */
				System.out.println(str);
			}
			
			System.out.println("-----------------------------");
		}
		return retObj;
	}
	/* Convert an Object array to Object list. */
	private static List<Object> objArrayToList(Object objArr[])
	{
		/* Declare return object. */
		List<Object> ret = new ArrayList<Object>();
		if(objArr!=null)
		{
			/* Get objArr size. */
			int objArrSize = objArr.length;
			
			/* Loop in the array, add each item to ret. */
			for(int i=0;i<objArrSize;i++)
			{
				ret.add(objArr[i]);
			}
			
			/* ret is editable. So can add item to it. */
			ret.add("Solr");
			/* Add String at specified index. */
			ret.add(2, "Lucent");
			
			/* Loop in ret.*/
			int size = ret.size();
			for(int i=0;i<size;i++)
			{
				Object obj = ret.get(i);
				/* Print out each item's value. */
				System.out.println(obj.toString());
			}
		}
		return ret;
	}
}

Download “JavaArrayToListConverter.zip” JavaArrayToListConverter.zip – Downloaded 32 times – 1,013 B

(Visited 60 times, 1 visits today)
READ :   How to add selenium server standalone jar file into your java project

Leave a Reply

Your email address will not be published. Required fields are marked *

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