根据Scala中“List of List”的条件创建地图 [英] Create map based on condition from Future of List in Scala
问题描述
我有一个param类型的方法 Future [List [MyRes]]
。 MyRes
有两个选项字段 id
和 name
。现在,我想要创建 id
和名称
的地图,如果两者都存在。我可以使用默认值创建地图,但是我不希望有默认值,只要跳过空值为0的条目。
I have method with param type Future[List[MyRes]]
. MyRes
has two option fields id
and name
. Now I want to create map of id
and name
if both present. I am able to create map with default value as follow but I don't want to have default value just skip the entry with null value on either.
def myMethod(myRes: Future[List[MyRes]]): Future[Map[Long, String]] = {
myRes.map (
_.map(
o =>
(o.id match {
case Some(id) => id.toLong
case _ => 0L
}) ->
(o.name match {
case Some(name) => name
case _ => ""
})
).toMap)
任何建议?
推荐答案
p>您正在寻找收集
:)
myRes.map {
_.iterator
.map { r => r.id -> r.name }
.collect { case(Some(id), Some(name) => id -> name }
.toMap
}
如果您的 MyRes
thingy是一个案例类,那么您不需要第一个 .map
:
If your MyRes
thingy is a case class, then you don't need the first .map
:
myRes.map {
_.collect { case MyRes(Some(id), Some(name)) => id -> name }
.toMap
}
收集
就像 .map
,但它需要一个PartialFunction,并跳过未定义的元素,它有点像你的匹配
语句,但没有默认值。
collect
is like .map
, but it takes a PartialFunction, and skips over elements on which it is not defined. It is kinda like your match
statement but without the defaults.
更新:
如果我正在正确阅读您的评论,并且您想要在任一字段为无,收集
将不会帮助,但您可以执行 flatMap
:
Update:
If I am reading your comment correctly, and you want to log a message when either field is a None, collect
won't help with that, but you can do flatMap
:
myRes.map {
_.flatMap {
case MyRes(Some(id), Some(name)) => Some(id -> name)
case x => loger.warn(s"Missing fields in $x."); None
}
.toMap
}
这篇关于根据Scala中“List of List”的条件创建地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!