RE: How do I transform a Java array into a List?

I have an array of integers in Java, and I need to transform it into a List. Could someone provide me with a step-by-step guide or some useful functions?

Add Comment
1 Answers
You can convert an array to a List in Java using the Arrays utility class that comes with Java. One of its static methods, `asList()`, does exactly this. Here's how you can do it: ```java Integer[] array = {1, 2, 3, 4, 5}; List list = Arrays.asList(array); ``` However, there's a caveat. This method returns a fixed-size List backed by the specified array. This means you can't add or remove elements from this list. If you need a modifiable List, you should create a new List object: ```java Integer[] array = {1, 2, 3, 4, 5}; List list = new ArrayList(Arrays.asList(array)); ``` Here, `new ArrayList()` creates a new ArrayList that's initialized with the elements of the array. If you are using Java 8 or above, you can use a Stream to convert a primitive array into a List: ```java int[] array = {1, 2, 3, 4, 5}; List list = Arrays.stream(array).boxed().collect(Collectors.toList()); ``` `Arrays.stream(array)` returns a Stream containing your array elements, `boxed()` wraps the int values with their equivalent Integer objects, and `collect()` collects them into a List. This returned List is normal and not backed by the array, so you can add or remove elements. Remember, the `Arrays.asList()` approach doesn't work with primitive arrays like `int[]`, `char[]` etc., because Java treats them as a single object rather than an array of objects, while both `ArrayList(Arrays.asList(array))` and `Stream` approaches work only with object arrays not with primitive arrays.
Answered on August 5, 2023.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.