Arrays
Convert Object Array to List example
With this example we are going to demonstrate how to convert an Object array to a List. We are using a String array in the example. In short, to convert an String array to a List you should:
- Create a String array with elements.
- Invoke
asList(Object[] objArray)
API method of Arrays, with the list as parameter. It returns a fixed sized list backed by the original array. - Invoke
iterator()
API method of List to obtain an Iterator of the list and then iterate through the list created from Array, withhasNext()
andnext()
API methods of iterator.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; import java.util.Arrays; import java.util.List; import java.util.Iterator; public class ConvertObjectArrayToList { public static void main(String[] args) { // create a String array String[] array = new String[] {"element_1","element_2","element_3","element_4","element_5"}; // static List asList(Object[] objArray) returns a fixed sized list backed by original array List list = Arrays.asList(array); // Iterate through the list created from Array Iterator it = list.iterator(); System.out.println("Elements in List : "); while(it.hasNext()) System.out.println(it.next()); } }
Output:
Elements in List :
element_1
element_2
element_3
element_4
element_5
This was an example of how to convert an Object array to a List in Java.
BAD !! The title says convert object array to list but the code converts String[] to list. Please pay attention while writing articles.