'Flatmap merging an internal iterator

I'm trying to convert an Iterator[String] to Iterator[CustomClass], where CustomClass is self-explanatory and doesn't need to have much detail here.

The workflow is:

Iterator[String] -> Iterator[Array[Byte]] -> Iterator[CustomClass]

What I have so far:

def extractAsCustomClass(strings: Iterator[String]): Iterator[CustomClass] = {
  val byteArrayIt = strings.flatMap(toByteArrayIterator)
  val customClassIt = byteArrayIt.flatMap(toCustomClassIterator)
  customClassIt
}

private def toByteArrayIterator(data: String): Iterator[Array[Byte]] = { // converts to byte array }
private def toCustomClassIterator(blob: Array[Byte]): Iterator[CustomClass] = { // converts to custom class }

With this, my end result is an Iterator[CustomClass] that contains one element where all the input byte arrays were combined into one byte array. So if I call extractAsCustomClass with a String iterator that has two elements, the end result would be Iterator[CustomClass] which only has one, combined element.

Using the example above of an input String iterator with two elements, I instead want an Iterator[CustomClass] that contains two CustomClass elements, where each String has gone from

String -> Array[Byte] -> CustomClass

I've tried playing around with map and flatMap but it either creates iterators of iterators or a combined element.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source