code: public static byte [] serialize(Serializable serializable, boolean compress) throws IOException {
          requireNonNull(serializable);
  
          try (ByteArrayOutputStream o = new ByteArrayOutputStream();
               ObjectOutputStream oos = new ObjectOutputStream(compress ? new GZIPOutputStream(o) : o)) {
              oos.writeObject(serializable);
              oos.flush();
              oos.close();  //must close before getting bytes because GZip streams require it.
              return o.toByteArray();
          }
      }
docs: Utility for turning a serializable object into a byte array. If the {@code compress} option is selected
  then the bytes will be run through gzip compression.