下表是学生信息表,包括姓名,性别,年龄
package com.sunyong
case class Student(name:String,sex:String,age:Int)
object StudentPractice {
def main(args: Array[String]): Unit = {
val s1 = Student("张三","男",16)
val s2 = Student("李四","女",17)
val s3 = Student("王五","男",18)
val s4 = Student("赵六","女",15)
val s5 = Student("何七","女",19)
val s6 = Student("宫八","男",20)
val s7 = Student("申九","女",16)
val s8 = Student("Rose","女",17)
val s9 = Student("Jhon","男",18)
val s10 = Student("Tim","女",15)
val s11 = Student("阿旭","男",19)
//放进studentList,遍历输出
val studentlist = List[Student](s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11)
println("******全部学生******")
studentlist.foreach(x=>println(x.toString))
//创建集合boyList、girlList、girlgt18List 、top3List、girlTop3List
val boyList = studentlist.filter(x=>x.sex.equals("男"))
println("******男学生******")
boyList.foreach(x=>println(x.toString))
val girlList = studentlist.filter(x=>x.sex.equals("女"))
println("******女学生******")
girlList.foreach(x=>println(x.toString))
val girlgt18ist =girlList.filter(x=>x.age>=18)
println("******大于等于18岁女学生******")
girlgt18ist.foreach(x=>println(x.toString))
println("******年龄最大的三个女生******")
val girlTop3List =girlList.sortBy(x=>x.age).drop(girlList.length-3)
girlTop3List.foreach(x=>println(x.toString))
//计算所有学生的平均年龄,所有男生的平均年龄,所有女生的平均年龄,打印输出
println("所有学生平均年龄:"+studentlist.map(x=>x.age).sum/studentlist.length.toDouble)
println("所有男学生平均年龄:"+boyList.map(x=>x.age).sum/boyList.length.toDouble)
println("所有女学生平均年龄:"+girlList.map(x=>x.age).sum/girlList.length.toDouble)
}
}
运行效果如下:
******全部学生******
Student(张三,男,16)
Student(李四,女,17)
Student(王五,男,18)
Student(赵六,女,15)
Student(何七,女,19)
Student(宫八,男,20)
Student(申九,女,16)
Student(Rose,女,17)
Student(Jhon,男,18)
Student(Tim,女,15)
Student(阿旭,男,19)
******男学生******
Student(张三,男,16)
Student(王五,男,18)
Student(宫八,男,20)
Student(Jhon,男,18)
Student(阿旭,男,19)
******女学生******
Student(李四,女,17)
Student(赵六,女,15)
Student(何七,女,19)
Student(申九,女,16)
Student(Rose,女,17)
Student(Tim,女,15)
******大于等于18岁女学生******
Student(何七,女,19)
******年龄最大的三个女生******
Student(李四,女,17)
Student(Rose,女,17)
Student(何七,女,19)
所有学生平均年龄:17.272727272727273
所有男学生平均年龄:18.2
所有女学生平均年龄:16.5