[英]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
:由于您需要同时
filter
和map
,您可以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.