Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala turning an Iterator[Option[T]] into an Iterator[T]

I have an Iterator[Option[T]] and I want to get an Iterator[T] for those Options where T isDefined. There must be a better way than this:

it filter { _ isDefined} map { _ get }

I would have thought that it was possible in one construct... Anybody any ideas?

like image 865
oxbow_lakes Avatar asked Mar 19 '09 23:03

oxbow_lakes


2 Answers

In the case where it is an Iterable

val it:Iterable[Option[T]] = ...
it.flatMap( x => x )                //returns an Iterable[T]

In the case where it is an Iterator

val it:Iterator[Option[T]] = ...
it.flatMap( x => x elements )       //returns an Iterator[T]
it.flatMap( _ elements)             //equivalent
like image 113
DRMacIver Avatar answered Sep 18 '22 22:09

DRMacIver


In newer versions this is now possible:

val it: Iterator[Option[T]] = ...
val flatIt = it.flatten
like image 23
soc Avatar answered Sep 20 '22 22:09

soc