如果我有一个像下面这样的案例类:
case class Student(name: String, activities: Seq[String], grade: String)
我有一个这样的列表:
val students = List(
Student("John", List("soccer", "Video Games"), "9th"),
Student("Jane", List("sword fighting", "debate"), "10th"),
Student("Boy Wonder", List("1", "5", "2"), "5th")
)
如何根据name
和activities
属性对内容进行排序以形成字符串?在上面的场景中,字符串将是:
boywonder_1_2_5_5th_jane_debate_swordfighting_10th_john_soccer_videogames_9th
在这种情况下,排序是这样完成的:
- 首先,元素用
name
排序 - 这就是为什么在最后一个字符串中boywonder
排在第一位的原因 - 然后元素的
activities
也按顺序排序 - 这就是为什么Boy Wonder's
活动被排序为1_2_5
您需要:
- 将所有内容设置为小写。
- 将内部列表排序
activities
。 - 按
name
对外部列表students
排序。 - 将所有内容转换为字符串。
这是代码。
students
.map { student =>
student.copy(
name = student.name.toLowerCase,
activities = student.activities.sorted.map(activity => activity.toLowerCase)
)
}.sortBy(student => student.name)
.map(student => s"${student.name}${student.activities.mkString}${student.grade}")
.mkString
.replaceAll("\s", "")
// res: String = "boywonder1255thjanedebateswordfighting10thjohnvideogamessoccer9th"