如何对案例类的内容进行排序



如果我有一个像下面这样的案例类:

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")
)

如何根据nameactivities属性对内容进行排序以形成字符串?在上面的场景中,字符串将是:

boywonder_1_2_5_5th_jane_debate_swordfighting_10th_john_soccer_videogames_9th

在这种情况下,排序是这样完成的:

  • 首先,元素用name排序 - 这就是为什么在最后一个字符串中boywonder排在第一位的原因
  • 然后元素的activities也按顺序排序 - 这就是为什么Boy Wonder's活动被排序为1_2_5

您需要:

  1. 将所有内容设置为小写。
  2. 将内部列表排序activities
  3. name对外部列表students排序。
  4. 将所有内容转换为字符串

这是代码。

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"

最新更新