Home > Enterprise >  Filter Option from a sequence in scala in effective way
Filter Option from a sequence in scala in effective way

Time:11-10

I want to get rid of .isDefined and .get, any good suggestions

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

I need my return type as Map[String, Seq[String]]

CodePudding user response:

Since you need to filter and map at the same time, you can collect:

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

The result of this is

Map("abc" -> Seq("abc", "abc"), "def" -> List("def"))

You can play around with this code here on Scastie.

You can read more about collect here on the official documentation.

  • Related