Home > Back-end >  Is there a simple way to turn an Iterator[Byte] into an inputstream lazily?
Is there a simple way to turn an Iterator[Byte] into an inputstream lazily?

Time:11-06

Given an Iterator[Byte] can I produce an InputStream without materializing the entire Iterator into memory?

CodePudding user response:

It is not too difficult. Just construct an InputStream and implement its read() method in terms of the Iterator. In Java it may look like this:

public InputStream streamFromIterator(Iterator<Byte> iterator) {
    return new InputStream() {

        @Override
        public int read() {
            if (iterator.hasNext())
                return Byte.toUnsignedInt(iterator.next());
            else
                return -1;  // end of stream
        }
    };
}

CodePudding user response:

If you are using Scala, there is a one line solution:

scala> import java.io.InputStream
                                                                                                                                                                           
scala> val itr = Iterator.range(0, 10).map(_.toByte)
val itr: Iterator[Byte] = <iterator>

scala> val ins: InputStream = () => if(itr.hasNext) itr.next & 255 else -1  // Here it is, or
//     val ins: InputStream = () => itr.nextOption.fold(-1)(_ & 255)
val ins: java.io.InputStream = anon$1@5dc218e2

scala> ins.readAllBytes()
val res0: Array[Byte] = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
  • Related