Scala如何单遍遍历学生序列从Map取分数并设置默认值
解决方案
核心前提:保证Student基于姓名匹配相等性
因为Map的键匹配依赖equals和hashCode,必须让姓名相同的Student实例被判定为相等:
- 最简便的方式是把
Student定义为case class,Scala会自动基于构造参数(这里是name)生成正确的equals和hashCode:case class Student(name: String) - 如果是普通类,必须手动重写这两个方法:
class Student(val name: String) { override def equals(other: Any): Boolean = other match { case that: Student => that.name == this.name case _ => false } override def hashCode(): Int = name.hashCode }
单遍遍历实现需求
原映射myMap的值类型不统一(包含字符串"100"和整数95),需要统一转换为Double,同时对缺失的学生返回默认值0.0。通过一次map遍历students序列即可完成:
方式1:先预处理映射(更高效,仅转换一次)
val students = Seq(Student("Roy"), Student("James"), Student("Rita")) val myMap = Map(Student("Roy") -> "100", Student("Rita") -> 95) // 预处理映射,将所有分数统一转为Double类型 val scoreMap = myMap.map { case (stu, score) => stu -> score.toString.toDouble } // 单遍遍历students,查映射并返回默认值 val resultSeq = students.map(stu => scoreMap.getOrElse(stu, 0.0)) // 输出:Seq(100.0, 0.0, 95.0)
方式2:遍历过程中直接处理类型转换
如果不想预处理映射,也可以在遍历每个学生时直接处理类型:
val resultSeq = students.map { stu => myMap.get(stu) match { case Some(s: String) => s.toDouble case Some(n: Int) => n.toDouble case None => 0.0 } }
说明
两种方式都是单遍遍历:students.map仅对序列做一次线性遍历,每个元素只处理一次,没有嵌套循环或多次遍历操作。
内容的提问来源于stack exchange,提问作者IUnknown
相关产品推荐
相关产品推荐

