Reputation: 1536
How do I convert a String
array to a java.util.List
?
Upvotes: 146
Views: 276026
Reputation: 193
If you have a list like this: "one, two, three."
You can use this code :
Arrays.asList(StringUtil.split("one, two, three",','))
or
public static List<String> convertStringToList(String listAsString) {
String[] list = listAsString.split("\\s*,\\s*");
return Arrays.stream(list).collect(Collectors.toList());
}
Upvotes: 1
Reputation: 301
If the result should be a readonly list then you can use List.of(nameOfArray)
@Test
public void shouldMapArrayToList(){
// given
var testArray = new String[]{"1", "2", "3" };
// when
List<String> result = List.of(testArray);
// then
assertEquals("1", result.get(0));
assertEquals("2", result.get(1));
assertEquals("3", result.get(2));
}
Upvotes: 1
Reputation: 44368
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());
Upvotes: 6
Reputation: 188
On Java 14 you can do this
List<String> strings = Arrays.asList("one", "two", "three");
Upvotes: 1
Reputation: 551
The Simplest approach:
String[] stringArray = {"Hey", "Hi", "Hello"};
List<String> list = Arrays.asList(stringArray);
Upvotes: 15
Reputation: 256
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);
Upvotes: 8
Reputation: 850
import java.util.Collections;
List myList = new ArrayList();
String[] myArray = new String[] {"Java", "Util", "List"};
Collections.addAll(myList, myArray);
Upvotes: 22
Reputation: 114757
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))
Upvotes: 289
Reputation: 1788
Use the static List list = Arrays.asList(stringArray)
or you could just iterate over the array and add the strings to the list.
Upvotes: 36