how to convert object to list in java

how to convert object to list in java

To convert an object to a List in Java, you can use the asList method of the Arrays class.

The asList method returns a fixed-size list backed by the specified array. This means that the list is a view of the original array, and any changes made to the list will be reflected in the array, and vice versa.

Here is an example of how you can use the asList method to convert an object to a List in Java:

ref‮re‬ to:lautturi.com
Object[] array = {"apple", "banana", "cherry"};
List<Object> list = Arrays.asList(array);

This code defines an Object array called array and assigns it an array of strings, and then uses the asList method to convert the array to a List. The resulting List is stored in a List variable called list.

Note that the asList method returns a list with a fixed size, so you cannot add or remove elements from the list. If you need to modify the list, you can create a new list from the array using the new ArrayList constructor, like this:

Object[] array = {"apple", "banana", "cherry"};
List<Object> list = new ArrayList<>(Arrays.asList(array));

This code creates a new ArrayList from the array using the Arrays.asList method, and stores the resulting List in a List variable called list. The ArrayList is a resizable list, so you can add or remove elements from it as needed.

Note that the Arrays.asList method only works for arrays of objects, not for primitive types such as int, double, or char. If you need to convert an array of primitive types to a list, you can use the boxed method of the Stream class to box the elements of the array into objects, and then use the collect method to collect the elements into a list.

Here is an example of how you can use the boxed and collect methods to convert an array of int values to a List in Java:

int[] array = {1, 2, 3};
List<Integer> list = Arrays.stream(array).boxed().collect(Collectors.toList());

This code defines an int array called array and assigns it an array of integers, and then uses the Arrays.stream method to create a stream from the array. It then uses the boxed method to box the elements of the array into Integer objects, and the collect method to collect the elements into a List. The resulting List is stored in a List variable called list.

Created Time:2017-11-01 12:05:15  Author:lautturi