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[]
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 😉
Top comments (3)
One thing I found useful in cases like this is to use
Function.identity()
. This can replacei ->i
in the call tomapToInt
. I prefer this because I think it is more obvious what is being done in the stream.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.After some googling, I founded this stackoverflow thread and replace the
i->i
byInteger::intValue
instead, which worked too.Nice! I think
identity()
returns an Integer in this case andmapToInt
expects anint
. There is no unboxing going on here. Sorry for the confusion.