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. :-)
Solution for Integer to int array conversion, without ArrayUtils:
final int[] arr = new int[wrapperArr.length];
Arrays.setAll(arr, i -> wrapperArr[i]);
And vice versa, int to Integer array:
final Integer[] wrapperArr = new Integer[arr.length];
Arrays.setAll(wrapperArr, i -> arr[i]);
Bonus:
ArrayList of Integers to int array.
final List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
final int[] arr = new int[list.size()];
Arrays.setAll(arr, list::get);
ArrayList of Integers (as Strings) to int array.
final List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
final int[] arr = new int[list.size()];
Arrays.setAll(arr, i -> Integer.parseInt(list.get(i)));