我想根据名称过滤员工并返回每位员工的身份
case class Company(emp:List[Employee])
case class Employee(id:String,name:String)
val emp1=Employee("1","abc")
val emp2=Employee("2","def")
val cmpy= Company(List(emp1,emp2))
val a = cmpy.emp.find(_.name == "abc")
val b = a.map(_.id)
val c = cmpy.emp.find(_.name == "def")
val d = c.map(_.id)
println(b)
println(d)
我想创建一个包含过滤器逻辑的通用函数,我可以为这些列表提供不同类型的列表和过滤器参数
Ex employeeIdByName
,其中包含参数
更新
eg :_.name and id
eg:cmpy.emp
值eg :abc/def
任何更好的方法来实现结果
我使用了map
和find
答案 0 :(得分:1)
如果你真的想要一个“通用”过滤器函数,它可以根据一组封闭的“允许”值过滤这些元素的任何属性的任何元素列表,同时映射结果对于其他一些财产 - 它看起来像这样:
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)
然而,这是一个非常简单的Scala操作的大量噪音:过滤和映射列表;这个特定的用例可以写成:
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
函数已经是“通用的”,因为它们可以通过适用于集合中元素的任何函数进行过滤/映射
答案 1 :(得分:0)
您可以使用Shapeless。如果您有VOLUMES
,则可以使用
employees: List[Employee]
将每个import shapeless._
import shapeless.record._
employees.map(LabelledGeneric[Employee].to(_).toMap)
转换为从字段键到字段值的映射。然后,您可以在地图上应用过滤器。