0

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?

7
  • Re: The other threads being "too old". The one about int[] has answers with Java 8 solutions. For byte[] 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. Commented Oct 13, 2019 at 4:05
  • @Thilo You found the answer in the other questions? Commented Oct 13, 2019 at 4:06
  • @ChepeQuestn All answers on stackoverflow.com/q/6860055/14955 work here Commented Oct 13, 2019 at 4:07
  • The user's question says: Is there another method instead for loop method? Commented Oct 13, 2019 at 4:10
  • 2
    @ChepeQuestn The answer by Tagir in the other linked question does provide an approach(toByteArray) which is coupled with the requirement of using lambda here. Apart from which the normal for loop can also be written using lambda as byte[] 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. Commented Oct 13, 2019 at 4:15

1 Answer 1

1

You can try doing like this:

listByte.stream().collect(ByteArrayOutputStream::new, (baos, i) -> baos.write((byte) i),
        (baos1, baos2) -> baos1.write(baos2.toByteArray(), 0, baos2.size()))
        .toByteArray()
Sign up to request clarification or add additional context in comments.

2 Comments

The combiner is only used in parallel streams, and it is kind of hard to reason about how that would work in this case. Better use a version of collect that does not support combinations.
Yeah, I agree this is not the easiest thing to deal with, thanks