如何分类案例类的内容 [英] How to sort contents of case class

查看:111
本文介绍了如何分类案例类的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个如下的案例类:

If I have a case class like below:

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属性对内容进行排序以形成字符串?在上述情况下,字符串为:

How can I sort the contents based on name and activities attributes to form a string? In the scenario above the string would be:

boywonder_1_2_5_5th_jane_debate_swordfighting_10th_john_soccer_videogames_9th

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

The sorting in this case is done like this:

  • 首先将元素按name进行排序-这就是为什么在最终字符串boywonder中排在第一位的原因
  • 然后元素的activities也要排序-这就是为什么Boy Wonder's活动被排序为1_2_5
  • 的原因
  • First the elements are sorted with name -- Thats why in the final string boywonder comes first
  • Then that elements' activities are sorted as well -- Thats why Boy Wonder's activities are sorted as 1_2_5

推荐答案

您需要:

  1. 将所有内容都小写.
  2. 排序内部列表activities.
  3. 将外部列表students排序为name.
  4. 将所有内容转换为 String .
  1. Make everything lowercase.
  2. Sort the inner list activities.
  3. Sort the outer list students, by name.
  4. Turn everything into a String.

这是代码.

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"

这篇关于如何分类案例类的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆