Scala
复制代码
object Test2 {
// 1. 创建学生信息数据结构和初始数据
def main(args: Array[String]): Unit = {
case class Student(name: String, age: Int, scores: List[Int])
val students = List(
Student("Alice", 21, List(90, 85, 88)),
Student("Bob", 19, List(78, 92, 85)),
Student("Charlie", 22, List(88, 77, 93)),
Student("David", 20, List(90, 88, 87)),
Student("Eve", 21, List(76, 85, 92))
)
// 创建迭代器并进行基础遍历
val studentIterator = students.iterator
while (studentIterator.hasNext) {
println(studentIterator.next().name)
}
// 3. 使用duplicate方法和筛选操作
val duplicatedIterator = students.iterator
val ageFiltered = students.filter(_.scores.head > 20) // 假设scores的第一个元素是年龄
val chineseFiltered = students.filter(_.scores.tail.last > 80) //
// 4. 使用zip方法关联信息
val averageScores = students.map(student => student.scores.sum / student.scores.size)
val zippedIterator = students.iterator.zip(averageScores.iterator)
while (zippedIterator.hasNext) {
val (student, avgScore) = zippedIterator.next()
println(s"${student.name} has an average score of $avgScore")
// 5. 打印前三名的同学信息
val topThree = students.take(3)
topThree.foreach(println)
// 6. 打印从第4名开始的后3位同学的信息
val fromFourthToSixth = students.drop(3).take(3)
fromFourthToSixth.foreach(println)
// 7. 重新创建学生列表的迭代器
// 用于统计所有学生的所有成绩的总和
// 打印结果
val totalScoresIterator = students.iterator.flatMap(_.scores)
val totalScores = totalScoresIterator.sum
println(s"Total scores: $totalScores")
// 8. 再次使用该迭代器,筛选出成绩列表中有至少一个特定分数以上的学生信息,并打印他们的姓名和年龄
val highScoreThreshold = 90
val highScoreStudents = students.filter(_.scores.exists(_ > highScoreThreshold))
highScoreStudents.foreach(student => println(s"Name: ${student.name}, Age: ${student.age}"))
}
}
}