Skip to main content

Posts

Showing posts from January, 2018

Using a Java stream (Java 8+) to convert List collection into primitive data type arrays

You need to convert an ArrayList<Integer> to int, similar case for others like Long > long. Prior to Java 8, you would have to try something like int[] myarray =   ll.toArray(new Integer[size]); But this will fail to compile! So it forces you to use Integer[] instead of int[]. However, you may have client code that expect int[] and not Integer[]. So the only other way would be to iterate over the list and convert to array the traditional way by adding element by element. Fine, but not elegant. I discovered that the stream based method above works even for primitive data types like int. So converting an array list of integers to an array is quite straightforward with a mapToInt () intermediate Intstream (or LongStream for long) as follows ArrayList<Integer>  ll  =  new  ArrayList<Integer>();       int[] myarray =  ll .stream().mapToInt( c  ->  c ).toArray(); The c-> c is just a lamda that says return the value c for each value in the str