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, with hasNext() and next() 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.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

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

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Rohit
Rohit
4 years ago

BAD !! The title says convert object array to list but the code converts String[] to list. Please pay attention while writing articles.

Back to top button