2017-09-05 175 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轉換爲地圖從外地鍵字段值。然後,您可以在地圖上應用濾鏡。