How to convert int[] into List<Integer> in Java?
To convert an int[]
array into a List<Integer>
in Java, you can use the Arrays.stream()
method to create a stream of the array, and then use the mapToObj()
method to map each element of the stream to an Integer
object. Finally, you can use the collect()
method to collect the elements of the stream into a List<Integer>
.
Here's an example of how to do this:
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
List<Integer> list = Arrays.stream(array)
.mapToObj(Integer::valueOf)
.collect(Collectors.toList());
System.out.println(list); // Outputs: [1, 2, 3, 4, 5]
}
}
This will create a List<Integer>
that contains the elements of the int[]
array.
Alternatively, you can use a loop to iterate over the elements of the array and add them to the List<Integer>
one by one.
Here's an example of how to do this:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {