Please Read first! My question is in Java 8,
Clearly, in time of these questions, java 8 did not exist yet.
How to convert an ArrayList containing Integers to primitive int array? for today 10 years! Convert ArrayList<Byte> into a byte[] for today 8 years!
I have this code:
List<Byte> listByte = new ArrayList<>();
// fill the List with Byte Wrapper...
Those result in errors:
// 1. option
byte[] arrayByte = listByte.stream().map(B -> B.byteValue()).toArray();
// 2. option
byte[] arrayByte = listByte.toArray(new byte[0]);
Is there another method instead for loop method?
int[]has answers with Java 8 solutions. Forbyte[]there is nothing new in Java 8, primitive streams have not been added to all types on purpose, see stackoverflow.com/q/32459683/14955 Either way, the linked answers still work.toByteArray) which is coupled with the requirement of using lambda here. Apart from which the normal for loop can also be written using lambda asbyte[] arrayBytes = new byte[listByte.size()]; IntStream.range(0, listByte.size()).forEach(i -> arrayBytes[i] = listByte.get(i));, if that qualifies as an answer to the question.