ArrayList of byte[] to byte[] using stream in Java

Viewed 11796

I have an ArrayList of byte[] and I'm wondering if it's possible to convert this to a byte[] using stream from Java 8. All the arrays inside the ArrayList have the same size.

ArrayList<byte[]> buffer = new ArrayList();

byte[] output = buffer.stream(...)
4 Answers

This is a possible solution with the Guava library:

List<byte[]> list = Arrays.asList("abc".getBytes(), "def".getBytes());
byte[] res = Bytes.toArray(list.stream()
        .map(byteArray -> Bytes.asList(byteArray))
        .flatMap(listArray -> listArray.stream())
        .collect(Collectors.toList()));
Related