Home > Mobile >  Filter Sequence of Option in scala equivalent without isDefined
Filter Sequence of Option in scala equivalent without isDefined

Time:11-10

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]]

CodePudding user response:

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)(_   _)

CodePudding user response:

So assuming all you want is a Map[String, Seq[String]] where the values are just the same key over and over again; you can do this:

t.collect {
  case A(Some(x)) if x.nonEmpty => x
}.groupBy(identity)

CodePudding user response:

I am assuming A is a case class with a single parameter of optional type. You can get the same result using the partial functions like

object FilterSeqOfOption extends App {

  case class A(x : Option[String])
  val t = Seq(A(Option("abc")), A(Option("abc")), A(Option("abc")), A(None))

 val res = t.collect { case A(Some(x)) => A(Option(x))
  }.groupBy{case A(Some(v)) => v}

  println(res)
}

Here collect first check whether partial function works for given value or not.

  • Related