How to create an ArrayList from array in Java?

+1 vote
182 views
asked Nov 21, 2020 by Rahul Singh (682 points)  

I have an array that looks like this

String[] array = {"a", "b", "c"};

I want to convert this into a List..

List<String> list = ????

1 Answer

0 votes
answered Dec 5, 2020 by Hitesh Garg (799 points)  
 
Best answer

Possible solutions for this are -

If immutable list is required

Arrays.asList(array);

If non-immutable list is required

new ArrayList<>(Arrays.asList(array));

Using Java Streams API

We can also use Java Streams API for this and in case we also want to transform and perform some operations on the elements then this will be a better approach to do things in a structured approach and also in minimal steps.

Arrays.stream(array).collect(Collectors.toList());

Example with the transformation to make all characters in uppercase.

Arrays.stream(array).map(String::toUpperCase).collect(Collectors.toList());
...