Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting String array to java.util.List

People also ask

Can we convert string array to list in java?

We can convert an array to arraylist using following ways. Using Arrays. asList() method - Pass the required array to this method and get a List object and pass it as a parameter to the constructor of the ArrayList class.

How will you convert a string array to an ArrayList?

To convert string to ArrayList, we are using asList() , split() and add() methods. The asList() method belongs to the Arrays class and returns a list from an array. The split() method belongs to the String class and returns an array based on the specified split delimiter.


List<String> strings = Arrays.asList(new String[]{"one", "two", "three"});

This is a list view of the array, the list is partly unmodifiable, you can't add or delete elements. But the time complexity is O(1).

If you want a modifiable a List:

List<String> strings = 
     new ArrayList<String>(Arrays.asList(new String[]{"one", "two", "three"}));

This will copy all elements from the source array into a new list (complexity: O(n))


Use the static List list = Arrays.asList(stringArray) or you could just iterate over the array and add the strings to the list.


import java.util.Collections;

List myList = new ArrayList();
String[] myArray = new String[] {"Java", "Util", "List"};

Collections.addAll(myList, myArray);

The Simplest approach:

String[] stringArray = {"Hey", "Hi", "Hello"};

List<String> list = Arrays.asList(stringArray);

First Step you need to create a list instance through Arrays.asList();

String[] args = new String[]{"one","two","three"};
List<String> list = Arrays.asList(args);//it converts to immutable list

Then you need to pass 'list' instance to new ArrayList();

List<String> newList=new ArrayList<>(list);

As of Java 8 and Stream API you can use Arrays.stream and Collectors.toList:

String[] array = new String[]{"a", "b", "c"};
List<String> list = Arrays.stream(array).collect(Collectors.toList());

This is practical especially if you intend to perform further operations on the list.

String[] array = new String[]{"a", "bb", "ccc"};
List<String> list = Arrays.stream(array)
                          .filter(str -> str.length() > 1)
                          .map(str -> str + "!")
                          .collect(Collectors.toList());