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中给出值?
答案 0 :(得分:3)
studentList.filter(_.courseName=="Math").map(_.stId)
答案 1 :(得分:2)
在不知道MutableList
到底是什么的情况下很难分辨。但假设它是scala.collection.mutable.MutableList
你可以这样做:
studentList.collect {
case s if s.courseName == "Math" => s.stId
}
答案 2 :(得分:0)
要查找注册了特定课程的学生,您可以使用filter
函数,该函数创建一个新集合,其中只包含给定函数返回的元素true
:
studentList.filter(_.courseName == "Math")
然后,要获取ID,您可以使用map
,它通过将给定函数应用于每个元素并收集结果来返回新集合:
studentList.filter(_.courseName == "Math").map(_.stId)
答案 3 :(得分:0)
使用collect,您只需遍历一次集合就可以实现您想要的结果!
studentList.collect {
case student if student.courseName == "Math" => student.stId
}
因此,只需一步即可有效收集过滤器和地图!