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

About Ilias Tsagklis

Avatar photo
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.

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

I have read and agree to the terms & conditions

 

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
3 years ago

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