2017-09-05 176 views
0

我要筛选基础上名员工,并返回每个员工筛选列表

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) 

我想创建一个包含过滤逻辑的通用功能的ID,我可以有不同那种列表和过滤参数列表那些

防爆employeeIdByName的这需要的参数

更新

  • 标准过滤器eg :_.name and id
  • 列表过滤eg:cmpy.emp
  • 比较eg :abc/def

什么更好的办法达到的效果 我用mapfind

+0

尝试过滤器功能。我不确定'比较'是什么意思。这不仅仅是过滤器的标准吗? – Tanjin

回答

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) 

然而,这是一个非常简单的斯卡拉操作周围的一吨噪音:筛选映射一个列表;这种特定用例可以写成:

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的内置mapfiltercollect功能是在这个意义上已经是“普通”,他们可以通过过滤/图任何适用于集合中元素的函数。

+0

你可以解释你的代码吗?我想返回员工的id。我不好,我会更新这个问题 – coder25

0

您可以使用无形。如果你有一个employees: List[Employee],你可以使用

import shapeless._ 
import shapeless.record._ 

employees.map(LabelledGeneric[Employee].to(_).toMap) 

给每个Employee转换为地图从外地键字段值。然后,您可以在地图上应用滤镜。