Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert from scala Iterator[T] to Option[T]

I tried to convert an iterator that should return a single item to an equivalent option.

The best I could do was this. Should I use something from standard API?

def toUniqueOption[T](a: Iterator[T]): Option[T] =
    if (a.size > 1)
      throw new RuntimeException("The iterator should be emtpy or contain a single item but contained ${a.size} items.")
    else if (a.size > 0)
      Option(a.toList(0))
    else
      Option.empty

Updated with try

def toUnique[T](a: Iterator[T]): Try[Option[T]] =
    if (a.size > 1)
      Failure(new RuntimeException("The iterator should be emtpy or contain a single item but contained ${a.size} items."))
    else if (a.size > 0)
      Success(Option(a.toList(0)))
    else
      Success(Option.empty)
like image 266
raisercostin Avatar asked Nov 29 '22 11:11

raisercostin


2 Answers

Calling size is risky because it isn't guaranteed to be efficient or even halt.

How about:

def toUniqueOption[T](a: Iterator[T]): Option[T] =
  a.take(2).toList match {
    case Nil => None
    case x :: Nil => Some(x)
    case _ => throw new RuntimeException("Iterator size > 1")
  }
like image 191
Chris Martin Avatar answered Dec 05 '22 13:12

Chris Martin


You could actually use standard API:

a.toStream.headOption

where a: Iterator[T]

Edit: with scala 2.13+ just use a.nextOption()

like image 22
jozik Avatar answered Dec 05 '22 13:12

jozik