我有一个类型为eval(function_str, { 'x' : x })
的列表,其中包含以下元素:
Example
我想在第三个字段中获取第一个元素Example("One", "1", null)
Example("Two", "1", null)
Example("Three", "2", someObject)
Example("Four", "3", someObject)
Example("Five", "3", null)
Example("Six", "3", someObject)
Example("Seven", "4", someObject)
,在第二个字段中获取null
。
在这种特定情况下,它将是第一个字段中带有"3"
的条目。
我该怎么做?什么是最好的功能方法呢?
答案 0 :(得分:5)
您可以使用List.collect
方法进行模式匹配:
list.collect{ case Example(x, "3", null) => x }
// res1: List[String] = List(Five)
答案 1 :(得分:1)
list.find(elem => elem._3 == null && elem._2 == "3")
或
list.find {
case Example(_, "3", null) => true
case _ => false
}
第一个解决方案有点难看,但如果你做的事情非常简单/小,它就避免了第二个(恕我直言)的额外代码