Based on the accepted answer to the following SO question...
ArrayList of byte[] to byte[] using stream in Java
and making a simple implementation of method toByteArray, hopefully the following provides what you require. (Notes after the code.)
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Arrays;
public class Foo {
public byte[] toByteArray() {
return new byte[]{(byte) -1};
}
public static void main(String[] args) {
Foo[] fooArray = new Foo[]{new Foo(), new Foo()};
byte[] bytes = Arrays.stream(fooArray)
.map(foo -> foo.toByteArray())
.collect(() -> new ByteArrayOutputStream(),
(b, e) -> b.write(e, 0, e.length),
(a, b) -> {
try {
b.writeTo(a);
}
catch (IOException x) {
throw new UncheckedIOException(x);
}
})
.toByteArray();
}
}
map returns a stream where every element in the stream is a byte array, i.e. byte[]. Then you simply collect all the bytes from all the byte arrays into a ByteArrayOutputStream. Then you call method toByteArray of class ByteArrayOutputStream.
Note that method writeTo throws IOException and checked exceptions are not simple to handle in lambda expressions. Hence it is wrapped in UncheckedIOException which is an unchecked exception.
flatMapinstead ofmap. However, it’s not quite as simple as that with arrays.toByteArray()for the objects?return new byte[] {validFlag, (byte) ((value>> Byte.SIZE) & BinaryDataUtil.BYTE_MASK), (byte) (value & BinaryDataUtil.BYTE_MASK) };toByteArrayvalues of {1,2} and {8,9}, the resulting value would be the byte array {1,2,8,9}?