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?

Andronicus
  • 25,419
  • 17
  • 47
  • 88
  • 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 https://stackoverflow.com/q/32459683/14955 Either way, the linked answers still work. – Thilo Oct 13 '19 at 04:05
  • @Thilo You found the answer in the other questions? –  Oct 13 '19 at 04:06
  • @ChepeQuestn All answers on https://stackoverflow.com/q/6860055/14955 work here – Thilo Oct 13 '19 at 04:07
  • The user's question says: Is there another method instead for loop method? –  Oct 13 '19 at 04:10
  • The for loop is the best method. But the accepted answer does not use a for loop. https://stackoverflow.com/a/6860106/14955 – Thilo Oct 13 '19 at 04:12
  • 2
    @ChepeQuestn The [answer by Tagir](https://stackoverflow.com/a/32470838/1746118) 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. – Naman Oct 13 '19 at 04:15
  • That same answer is also given right here (https://stackoverflow.com/a/58360450/14955). But I would a) question the "requirement" of using lambda and b) take a hint from lack of ByteStreams and try to avoid having a `List` in the first place. Practically all byte-manipulating libraries work with `byte[]` or `ByteBuffer`. – Thilo Oct 13 '19 at 04:19

1 Answers1

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()
Andronicus
  • 25,419
  • 17
  • 47
  • 88
  • 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. – Thilo Oct 13 '19 at 03:57
  • Yeah, I agree this is not the easiest thing to deal with, thanks – Andronicus Oct 13 '19 at 03:59