In your example, you are writing a compressed stream to a ByteArrayOutputStream. Your compressed array must exist somewhere, and if the goal is memory, then ByteArrayOutputStream is your likely choice. You can also write a stream to a socket or file. In this case, you will not duplicate the stream in memory. If your array is 800 MB and your computer runs at 1 GB, you can easily write the array to a compressed file with the example you provided. This change will replace ByteArrayOutputStream with the file stream.
The ObjectOutputStream format is actually quite efficient. It will not duplicate your array in memory and has special code for efficiently writing arrays.
Want to work with a compressed array in memory? Will you use data for a sparse array? A rare array is good when you have large gaps in your data.
source share