Java List Integer To Int Array

Java List Integer To Int Array | Here we will discuss how to convert an integer list to an int array in Java. In Java, there are various methods to convert the object to a primitive data type. We will see some of them here.

Following are the different ways to convert List Integer To int Array:-

  1. By using streams from Java 8
  2. By using Apache Commons Lang

Convert Integer List To int Array in Java using Streams

First, let us see how to convert a list integer to an int array by using the streams from Java 8. The first step here is to convert the integer list to an array list by the stream() method and then convert the Stream to int[ ].

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(6, 5, 88, 44, 22, 77, 11, 12, 12, 23, 56);
        System.out.println("Type of list: " + list.getClass().getName());

        // convert Integer List To int Array
        int[] intArray = list.stream().mapToInt(Integer::intValue).toArray();

        System.out.println("Type of intArray: " + intArray.getClass().getName());
        System.out.println("The Integer array after converting to int array is: ");
        System.out.println(Arrays.toString(intArray));
    }
}

Output:-

Type of list: java.util.Arrays$ArrayList
Type of intArray: [I
The Integer array after converting to int array is:
[6, 5, 88, 44, 22, 77, 11, 12, 12, 23, 56]

Java List Integer To Int Array using toPrimitive()

Apache commons lang library also contains some methods to convert Integer List to an int array. The ArrayUtils class contains toPrimitive() as follows:- public static int[ ] toPrimitive(final Integer[ ] array)

To call this toPrimitive() method we need to pass an Integer[ ] array but not the Integer list. Therefore first we have to convert the Integer list to an Integer array by using the List.toArray() method. The below program demonstrates the conversion of List Integer to int Array in Java:-

import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;

public class Main {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(78, 56, 14, 23, 89, 45, 36, 22);
        int[] intArray = ArrayUtils.toPrimitive(list.toArray(new Integer[0]));
        System.out.println(Arrays.toString(intArray));
    }
}

Output:-

[78, 56, 14, 23, 89, 45, 36, 22]

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *