在 scala 的对象列表中找到一个 属性 值

Find a property value in the list of objects in scala

 class Student {
  var name: String = _
  var stId: String = _
  var courseName: String = _
}

object Student {
  def apply(name: String, stId: String, courseName: String): Student = {
    var s = new Student
    s.name = name
    s.stId = stId
    s.courseName = courseName
    s
  }
}

val studentList :MutableList[Student]= MutableList()
studentList+=(Student("Alex","TI178","Math"))
studentList+=(Student("Bob","TI654","Comp"))
studentList+=(Student("Sam","TI1115","Comp"))
studentList+=(Student("Don","TI900","Math"))

如何在上面的 MutableList 中找到 "Math" 注册的 student.stId 或给定值的列表?

studentList.filter(_.courseName=="Math").map(_.stId)

要查找注册给定课程的学生,您可以使用 filter 函数,该函数创建一个新集合,其中仅包含给定函数 returns true 的元素:

studentList.filter(_.courseName == "Math")

然后,要获取 ID,您可以使用 map,通过将给定函数应用于每个元素并收集结果,returns 一个新集合:

studentList.filter(_.courseName == "Math").map(_.stId)

如果不知道 MutableList 到底是什么,就很难说清楚。但假设它是 scala.collection.mutable.MutableList 你可以这样做:

studentList.collect { 
  case s if s.courseName == "Math" => s.stId 
}

使用collect,只需要遍历一次集合,就可以达到你想要的结果!

studentList.collect { 
  case student if student.courseName == "Math" => student.stId 
}

如此有效,收集就是过滤和映射,只需一步!