创建迭代器并进行基础遍历
package test_28 // 1. 创建表示学生信息的类并初始化学生对象列表 case class Student(name: String, age: Int, scores: List[Double]) object 迭代器1 { def main(args: Array[String]): Unit = { // 创建学生对象并存储在列表中 val studentList = List( Student("小张", 18, List(88.0, 85.0, 90.0)), Student("小卢", 18, List(90.0, 97.0, 85.0)), Student("小王", 19, List(98.0, 80.0, 95.0)), Student("小朱", 21, List(90.0, 85.0, 90.0)), Student("小沈", 19, List(88.0, 90.0, 90.0)) ) // 2. 创建迭代器并进行基础遍历 val studentIterator = studentList.iterator while (studentIterator.hasNext) { val student = studentIterator.next() println(s"学生姓名: ${student.name}") } // 3. 使用duplicate方法和筛选操作 val (originalIterator, duplicateIterator) = studentList.iterator.duplicate val filteredByAge = originalIterator.filter(_.age > 20) val filteredByChineseScore = duplicateIterator.filter(student => student.scores(2) > 80) println("年龄大于20岁的同学:") filteredByAge.foreach(student => println(s"姓名: ${student.name}, 年龄: ${student.age}")) println("语文成绩大于80分的同学:") filteredByChineseScore.foreach(student => println(s"姓名: ${student.name}, 语文成绩: ${student.scores(2)}")) // 4. 使用zip方法关联信息 val averageScoresList = studentList.map(student => student.scores.sum / student.scores.size) val averageScoresIterator = averageScoresList.iterator val zippedIterator = studentList.iterator.zip(averageScoresIterator) println("学生姓名和平均成绩:") zippedIterator.foreach { case (student, averageScore) => println(s"姓名: ${student.name}, 平均成绩: ${averageScore}") } // 5. 打印前三名的同学信息 val topThreeStudents = studentList.sortBy(-_.scores.sum).take(3) println("前三名同学信息:") topThreeStudents.foreach(student => println(s"姓名: ${student.name}, 年龄: ${student.age}, 成绩总和: ${student.scores.sum}")) // 6. 打印从第4名开始的后3位同学的信息 val fourthAndNextThreeStudents = studentList.sortBy(_.scores.sum).drop(3).take(3) println("从第4名开始的后3位同学信息:") fourthAndNextThreeStudents.foreach(student => println(s"姓名: ${student.name}, 年龄: ${student.age}, 成绩总和: ${student.scores.sum}")) // 7. 重新创建学生列表的迭代器,用于统计所有学生的所有成绩的总和,并打印结果 val allScoresIterator = studentList.iterator var totalScore = 0.0 while (allScoresIterator.hasNext) { val student = allScoresIterator.next() totalScore += student.scores.sum } println(s"所有学生的所有成绩总和: ${totalScore}") // 8. 再次使用该迭代器,筛选出成绩列表中有至少一个特定分数以上的学生信息,并打印他们的姓名和年龄 val specificScore = 90.0 val filteredStudents = studentList.iterator.filter(student => student.scores.exists(_ > specificScore)) println(s"成绩中有至少一个${specificScore}分以上的学生信息:") filteredStudents.foreach(student => println(s"姓名: ${student.name}, 年龄: ${student.age}")) } }
原文地址:https://blog.csdn.net/yzj231128/article/details/144336926
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!