简体   繁体   English

以有效的方式从 Scala 中的序列过滤选项

[英]Filter Option from a sequence in scala in effective way

I want to get rid of .isDefined and .get , any good suggestions我想摆脱.isDefined.get ,任何好的建议

 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]]我需要我的返回类型为Map[String, Seq[String]]

Since you need to filter and map at the same time, you can collect :由于您需要同时filtermap ,您可以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 .您可以在 Scastie 上使用此代码。

You can read more about collect here on the official documentation .您可以在官方文档中阅读有关collect更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM