Home » Core Java » util » Arrays » Convert Object Array to List example

About Ilias Tsagklis

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

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.

(No Ratings Yet)
1 Comment Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Rohit Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Rohit
Guest
Rohit

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