Search code examples
scala

Filter Sequence of Option in scala equivalent without isDefined


I want to get rid of isDefined and get

val t = Seq(A(Option("abc")), A(Option("abc")), A(Option("abc")), A(None))
t.filter(_.x.isDefined).groupBy(e=>e.x.get)

The code is complex , result I need is Map[String,Seq[String]]


Solution

  • You could groupBy x instead of x.get and then flatMap the result to filter out the None group and extract the value from the Somes in one go.

    t.groupBy(_.x).flatMap{ case (keyOpt, value) => keyOpt.map(_ -> value) }
    

    That has the same effect as the code you posted. However if you want a Map[String,Seq[String]] instead of a Map[String,Seq[A]] you could do this instead:

    t.flatMap(_.x).groupBy(identity)
    

    Though grouping by identity might be a bit weird unless your ultimate goal is simply to count:

    t.flatMap(_.x).groupMapReduce(identity)(_ => 1)(_ + _)