Signup/Sign In
PUBLISHED ON: JANUARY 28, 2021

Convert Integer List to Int Array in Java

In this article, we will learn how to convert Integer List to int Array in Java. There are two ways to Convert Integer List to array in Java

  1. Using stream.mapToInt() method
  2. Using ArrayUtils.toPrimitive() method

Example: Converting Integer List to an Array using stream.mapToInt() method

In this example, we created a list of integers. To change this ArrayList to the Array we called stream().mapToInt().toAttay() method on the list and the result of this will be assigned to array arr.

import java.util.*;
public class StudyTonight 
{
	public static void main(String[] args) 
	{
		List<Integer> list = new ArrayList<Integer>();
		list.add(1);
		list.add(2);
		list.add(3);
		list.add(4);
		list.add(5);
		int[] arr = list.stream().mapToInt(i->i).toArray();
		for (int val : arr) {
			System.out.println(val);
		}
	}
}


1
2
3
4
5

Example: Converting Integer List to Int Array using ArrayUtils.toPrimitive() method

For this example, we need an external package org.apache.commons.lang3.ArrayUtils. In some IDE, you can find it already or you need to import it by downloading the JARs file.

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
public class StudyTonight 
{
	public static void main(String[] args) 
	{
		List<Integer> list = new ArrayList<Integer>();
		list.add(1);
		list.add(2);
		list.add(3);
		list.add(4);
		list.add(5);
		int[] arr = ArrayUtils.toPrimitive(list.toArray(new Integer[list.size()]));
		for (int val : arr) {
			System.out.println("int primitive: "+val);
		}
	}
}


1
2
3
4
5

Conclusion:

We learned how to convert integer list to int array in java. There are two methods to do that ArrayUtils.toPrimitive() and stream().mapToInt() of stram API in Java.



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.