用另一个替换列表元素并返回新列表

时间:2019-09-16 04:40:26

标签: scala

我对此很执着,我知道这是一个很简单的问题:(

我有一个案例类,例如:

case class Students(firstName: String, lastName: String, hobby: String)

我需要返回一个新列表,但要根据学生姓名更改hobby的值。例如:

val classToday = List(Students("John","Smith","Nothing"))

如果学生姓名为John,我想将爱好更改为Soccer,那么结果列表应该是:

List(Students("John","Smith","Soccer")

我认为这可以通过地图完成?我尝试过:

classToday.map(x => if (x.firstName == "John") "Soccer" else x)

这只会将firstName替换为我不想要的Soccer,我尝试将“ True”条件设置为x.hobby == "Soccer",但这不起作用。

我认为对此有一个简单的解决方案:(

4 个答案:

答案 0 :(得分:3)

map中的lambda函数必须再次返回Students值,而不仅仅是"Soccer"。例如,如果您必须用"Soccer"替换每个人的爱好,那是不对的:

classToday.map(x => "Soccer")

您想要的是the copy function

classToday.map(x => x.copy(hobby = "Soccer"))

或者对于原始任务:

classToday.map(x => if (x.firstName == "John") x.copy(hobby = "Soccer") else x)

答案 1 :(得分:1)

您可以使用模式匹配语法来修饰这种类型的过渡。

val newList = classToday.map{
                case s@Students("John",_,_) => s.copy(hobby = "Soccer")
                case s => s
              }

答案 2 :(得分:0)

我建议使其更通用,您可以创建姓名与兴趣的映射:

例如:

val firstNameToHobby = Map("John" -> "Soccer", "Brad" -> "Basketball")

并按如下所示使用它:

case class Students(firstName: String, lastName: String, hobby: String)

val classToday = List(Students("John","Smith","Nothing"), Students("Brad","Smith","Nothing"))

val result = classToday.map(student => student.copy(hobby = firstNameToHobby.getOrElse(student.firstName, "Nothing"))) 

// result = List(Students(John,Smith,Soccer), Students(Brad,Smith,Basketball))

答案 3 :(得分:0)

最好在具有Hobby的学生的firstName之间创建一个映射,然后按以下方式使用它:

scala> val hobbies = Map("John" -> "Soccer", "Messi" -> "Soccer", "Williams" -> "Cricket")
hobbies: scala.collection.immutable.Map[String,String] = Map(John -> Soccer, Messi -> Soccer, Williams -> Cricket)

scala> case class Student(firstName: String, lastName: String, hobby: String)
defined class Student

scala> val students = List(Student("John", "Smith", "Nothing"), Student("Williams", "Lopez", "Nothing"), Student("Thomas", "Anderson", "Nothing"))
students: List[Student] = List(Student(John,Smith,Nothing), Student(Williams,Lopez,Nothing), Student(Thomas,Anderson,Nothing))

scala> students.map(student => student.copy(hobby = hobbies.getOrElse(student.firstName, "Nothing")))
res2: List[Student] = List(Student(John,Smith,Soccer), Student(Williams,Lopez,Cricket), Student(Thomas,Anderson,Nothing))