How to

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 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 my_list = new ArrayList(); // 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 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

Votre commentaire

Entrez vos coordonnées ci-dessous ou cliquez sur une icône pour vous connecter:

Logo WordPress.com

Vous commentez à l’aide de votre compte WordPress.com. Déconnexion /  Changer )

Photo Google

Vous commentez à l’aide de votre compte Google. Déconnexion /  Changer )

Image Twitter

Vous commentez à l’aide de votre compte Twitter. Déconnexion /  Changer )

Photo Facebook

Vous commentez à l’aide de votre compte Facebook. Déconnexion /  Changer )

Connexion à %s