1

i have an array of Objects. Those objects offer the method toByteArray(). If i call foo.toByteArray() I will get the byte-representation of this object.

I am struggling to convert this array of objects into a byte array.

My first approach was:

Arrays.stream(fooArray).map((fooEntry) -> fooEntry.toByteArray()).toArray();

However, this does return an array of objects instead of byte[]. What's the easiest way to do what I want?

4
  • Conceptually you need to use flatMap instead of map. However, it’s not quite as simple as that with arrays. Commented Aug 18, 2021 at 8:22
  • What is your implementation of toByteArray() for the objects? Commented Aug 18, 2021 at 8:25
  • Basically the object represents a byte value and a short value. And toByteArray does the following: return new byte[] {validFlag, (byte) ((value>> Byte.SIZE) & BinaryDataUtil.BYTE_MASK), (byte) (value & BinaryDataUtil.BYTE_MASK) }; Commented Aug 18, 2021 at 8:36
  • Did you want all the byte arrays concatenated together? For instance, if the two objects in your array have toByteArray values of {1,2} and {8,9}, the resulting value would be the byte array {1,2,8,9}? Commented Dec 7, 2024 at 0:08

2 Answers 2

0

An array is serializable, so as long as your Objects are also serializable then you should be able to convert the Array to a byte[] without having to access the toByteArray() method of the elements.

First make sure your Object is Serializable:

public class MyObject implements Serializable {
//... Your class 
}

Now you should be able to serialise the whole Array using ByteArrayOutputStream:

ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(fooArray);
oos.flush();
byte[] byteArray = bos.toByteArray();

I'm not sure if this is the best approach as I'm quiet new to Java, but this should work.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.