Java Example – String Array To List




Java Tutorial for Beginners
Java Tutorial for Beginners
Java Tutorial for Beginners
Java Tutorial for Beginners

In this Java Example we will learn How To convert String Array To List Example.This Java Example, String Array To List shows how to convert Java String array to java.util.List object using Arrays.asList method.
To covert String array to java.util.List object, use List asList(String[] strArray) method of Arrays class.
Please note that list object created using this method can not be modified. Any attempt to call add or delete method would throw UnsupportedOperationException exception.

 

/**
 * Java String Array To List Example  by codebind.com.
 */
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Arrays;

public class JavaStringArrayToList {

    public static void main(String args[]){

        //create String array
        String[] names = new String[]{"Lina", "alina", "Tom", "Jack", "harry", "Ram"};


        List list = (List) Arrays.asList(names);

        //display elements of List
        System.out.println("converted String array to List");
        for(int i=0; i < list.size(); i++){
            System.out.println(list.get(i));
        }

        /*
        * If you want modifiable list object, then use
        * ArrayList list = (ArrayList) Arrays.asList(names);
        */
        /* Alternate Method to covert String array to List */
        List anotherList = new ArrayList();

        Collections.addAll(anotherList, names);
    }
}

/*
Output:
converted String array to List
Lina
alina
Tom
Jack
harry
Ram
*/

 
 





Partner Sites

VideoToGifs.com

EasyOnlineConverter.com

SqliteTutorials.com





Be the first to comment

Leave a Reply

Your email address will not be published.


*