https://codeahoy.com/java/How-To-Convery-ArrayList-To-Array/
Method 1-
public static int[] convertIntegers(List<Integer> integers)
{
int[] ret = new int[integers.size()];
for (int i=0; i < ret.length; i++)
{
ret[i] = integers.get(i).intValue();
}
return ret;
}
Method 2-
List<Integer> ans = new ArrayList<Integer>();
int[] n = (int[])ans.toArray(int[ans.size()]);
Method 3- using Steam
int[] arr = list.stream().mapToInt(i -> i).toArray();
If you are using java-8 there's also another way to do this.
int[] arr = list.stream().mapToInt(i -> i).toArray();
What it does is:
getting a Stream from the list
obtaining an IntStream by mapping each element to itself (identity function), unboxing the int value hold by each Integer object (done automatically since Java 5)
getting the array of int by calling toArray
You could also explicitly call intValue via a method reference, i.e:
int[] arr = list.stream().mapToInt(Integer::intValue).toArray();
Top comments (1)
Hi there, we encourage authors to share their entire posts here on DEV, rather than mostly pointing to an external link. Doing so helps ensure that readers don’t have to jump around to too many different pages, and it helps focus the conversation right here in the comments section.
If you choose to do so, you also have the option to add a canonical URL directly to your post.