I have created an ArrayList of Integer wrapper class, then converted it into Integer type array. Now my goal is to convert it into int type array. Try to solve the problem using ArrayUtils.toPrimitive() method. But it's having some issues. Here is my code:
import java.util.ArrayList;
import java.util.Arrays;
import java.lang.Object;
public class ArrayListToArray {
public static void main(String[] args) {
// Convert to int array in one line
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(Integer.parseInt("1"));
list.add(Integer.parseInt("2"));
list.add(Integer.parseInt("3"));
list.add(Integer.parseInt("4"));
Integer[] wrapperArr = list.toArray(new Integer[list.size()]);
// If you want a `primitive` type array
int[] arr = ArrayUtils.toPrimitive(wrapperArr);
System.out.println(Arrays.toString(arr));
}
}
It's showing error ArrayUtils can't be resolved. And now executing the code.
How to solve the problem without writing any loop ? I am exploring java built-in classes, methods and packages.
Or is there any other methods other than ArrayUtils, to do the same ?
Thanks in advance. :-)
int[] arr = list.stream().mapToInt(Integer::valueOf).toArray();ArrayUtilswith:import org.apache.commons.lang3.ArrayUtils;.