DEV Community

10x learner
10x learner

Posted on • Originally published at 10xlearner.com on

How to convert a Java List to int []

Hello ! I’m Xavier Jouvenot and in this small post, I am going to explain how to convert a Java List<Integer> to int [].

Self promotion: You can find other articles on Android development on my website 😉

Solution

For the people who only want the solution, to quickly copy-paste it in there code, here it is 😉

List<Integer> my_list = new ArrayList<Integer>(); // create the list
// some code to fill the list...
int [] my_array = my_list.stream().mapToInt(i->i).toArray(); //convert the list into a int[]

Enter fullscreen mode Exit fullscreen mode

Explanation

If you read this, it may be that you want to understand how the previous solution achieve the goal of transforming the List<Integer> into a int [], and this is what I am going to try to explain. 🙂

First of all, we take the filled list and we call the method stream, which is going to convert our List into a Stream. A Stream is "A sequence of elements supporting sequential and parallel aggregate operations.", as defined by the documentation. And with this class, we are one step closer from the type we want.

Then, we call the function mapToInt from the Stream class. This method returns a IntStream containing the result of the operations passed in parameter, and since we are telling it to not change the value of the element (i stays i), all this function does is to convert the Stream into a IntStream.

Finally, we call the method toArray of the class IntStream. This method convert the IntStream to a int [], which is exactly what we aimed for. 🙂


Thank you all for reading this article,And until my next article, have a splendid day 😉

Interesting links

Top comments (3)

Collapse
 
moaxcp profile image
John Mercier

One thing I found useful in cases like this is to use Function.identity(). This can replace i ->i in the call to mapToInt. I prefer this because I think it is more obvious what is being done in the stream.

Collapse
 
10xlearner profile image
10x learner

Hi John Mercier !

Thank you for you comment :)

I didn't know about Function.identity(), and, since I like to have the more explicit code possible, I tried it, but I obtained an error.

error: incompatible types: no instance(s) of type variable(s) T exist so that Function<T,T> conforms to ToIntFunction<? super Integer>

After some googling, I founded this stackoverflow thread and replace the i->i by Integer::intValue instead, which worked too.

Collapse
 
moaxcp profile image
John Mercier

Nice! I think identity() returns an Integer in this case and mapToInt expects an int. There is no unboxing going on here. Sorry for the confusion.