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
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.int[] myarray = ll.toArray(new Integer[size]);
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
The c-> c is just a lamda that says return the value c for each value in the stream, unmodified. Because this is an IntStream stream, it has a method that returns int[] and this works for this case.ArrayList<Integer> ll = new ArrayList<Integer>();int[] myarray = ll.stream().mapToInt(c -> c).toArray();
Comments
Post a Comment