如果你真的想要一个“通用”的过滤功能,可以过滤呃,通过这些元素的任何属性的基础上,闭集的“允许”元素的任意值列表,而测绘成果到一些其他财产 - 这将是这个样子:
def filter[T, P, R](
list: List[T], // input list of elements with type T (in our case: Employee)
propertyGetter: T => P, // function extracting value for comparison, in our case a function from Employee to String
values: List[P], // "allowed" values for the result of propertyGetter
resultMapper: T => R // function extracting result from each item, in our case from Employee to String
): List[R] = {
list
// first we filter only items for which the result of
// applying "propertyGetter" is one of the "allowed" values:
.filter(item => values.contains(propertyGetter(item)))
// then we map remaining values to the result using the "resultMapper"
.map(resultMapper)
}
// for example, we can use it to filter by name and return id:
filter(
List(emp1, emp2),
(emp: Employee) => emp.name, // function that takes an Employee and returns its name
List("abc"),
(emp: Employee) => emp.id // function that takes an Employee and returns its id
)
// List(1)
然而,这是一个非常简单的斯卡拉操作周围的一吨噪音:筛选和映射一个列表;这种特定用例可以写成:
val goodNames = List("abc")
val input = List(emp1, emp2)
val result = input.filter(emp => goodNames.contains(emp.name)).map(_.id)
甚至:
val result = input.collect {
case Employee(id, name) if goodNames.contains(name) => id
}
Scala的内置map
,filter
,collect
功能是在这个意义上已经是“普通”,他们可以通过过滤/图任何适用于集合中元素的函数。
尝试过滤器功能。我不确定'比较'是什么意思。这不仅仅是过滤器的标准吗? – Tanjin