How to convert List<Integer> to int[] in java using streams

ยท

2 min read

How to convert  List<Integer> to int[] in java using streams

Streams in java can do such much that we don't even know about !

I was struggling with this problem for some time and then I got the perfect answer.

The easy but long for loop way below !

List<Integer> list = new ArrayList();
list.add(1);
list.add(2);
list.add(3);

int [] arr = new int[list.size()];
for (int i = 0; i < arr.length; i++) {
       arr[i] = Integer.valueOf(list.get(i));
}

for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + "\t");
}

If you are someone like me and you don't want to write so much for doing a simple conversion you will definitely like whats coming next.

Streams to the rescue !

With streams you can do this in a single line and it looks way more elegant and easy to understand.

Let's take a look at how the solution will look like and then we will try to understand the same. Here it goes !

int[] arr = list.stream().mapToInt(i -> i).toArray();
  1. So what we are doing in "list.stream()" is creating a Stream of Integers from List of Integers.

  2. After creating a stream of "Integer" now we want to convert it to stream of "int" (the primitive type).

  3. The Stream#toArray function returns Object[] so we can't use it directly, Also in Stream#toArray(IntFunction generator) A can't represent primitive int.

  4. We don't want the stream to return Object[] or Integer[] so what we can do instead is convert Stream to IntStream.

  5. "Stream#mapToInt(ToIntFunction<? super T> mapper)" method comes to the rescue. We can pass a lambda to it which maps Integer to int.

     list.stream().mapToInt(Integer::intValue).toArray();  OR  list.stream().mapToInt(i -> 
     i.intValue()).toArray();
    
  6. Unboxing can help it shorten even more !. Since compiler knows that result of this lambda must be int (lambda in "mapToInt" is implementation of "ToInt" Functional interface for "int applyAsInt(T value)" method which is expected to return int). So we can simply write it as "mapToInt(i -> i)".

    list.stream().mapToInt(i -> i).toArray();
    

Hurray we reached an end! Please follow me here for some more interesting blogposts! Functional interface post coming next ! We'll explore different kinds of functional interfaces inbuilt in java and how to create one ourselves !

ย