如何分类案例类的内容 [英] How to sort contents of case class
本文介绍了如何分类案例类的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个如下的案例类:
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")
)
如何根据name
和activities
属性对内容进行排序以形成字符串?在上述情况下,字符串为:
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 stringboywonder
comes first - Then that elements'
activities
are sorted as well -- Thats whyBoy Wonder's
activities are sorted as1_2_5
推荐答案
您需要:
- 将所有内容都小写.
- 排序内部列表
activities
. - 将外部列表
students
排序为name
. - 将所有内容转换为 String .
- Make everything lowercase.
- Sort the inner list
activities
. - Sort the outer list
students
, byname
. - 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屋!
查看全文