获取集合的大小
list.size
获取集合的长度
list.length
是否包含
val list = List[Int](3,7,2,9,10)
list.contains(100
转字符串,参数是元素的分隔符。
val list = List(1, 2, 3, 4)
println(list.mkString("-"))//结果:1-2-3-4
删除前[后]多少个元素,保留剩下的元素
val list1 = list.drop(3)
val list2 = list.dropRight(3)
val list14 = List[String]("name","age","address","sex","aa")
val list15 = List[Any]("zhangsan",20,"shenzhen","男")
val list16 = list14.zip(list15)
println(list16)// List((name,zhangsan), (age,20), (address,shenzhen), (sex,男))
返回一个二元元祖,2个List
//list16:((name,zhangsan), (age,20), (address,shenzhen), (sex,男))
val list17 = list16.unzip
println(list17)//(List(name, age, address, sex),List(zhangsan, 20, shenzhen, 男))
//排序,升序
val list1 = list.sorted
//降序
val list2 = list.sorted.reverse
默认升序
val list3 = List[(String,Int)]( ("zhangsan",20),("lisi",30),("wangwu",15),("zhaoliu",5) )
val list = list3.sortBy(_._1)
// 函数体中< 代表是升序 >代表是降序
val list5 = list3.sortWith((x,y)=>x._2<y._2)
//升序
val list7 = list3.sortWith(_._2<_._2)
println(list7)//List((zhaoliu,5), (wangwu,15), (zhangsan,20), (lisi,30))
//降序
val list6 = list3.sortWith((x,y)=>x._2>y._2)
println(list6)//List((lisi,30), (zhangsan,20), (wangwu,15), (zhaoliu,5))
对list每个元素都执行一次,返回一个新的list
val list8 = List[String]("hello","word","python","hadoop")
val list9 = list8.map(x=>x.length)//List(5, 4, 6, 6)
class Person(val name:String,val age:Int)
val list10 = List[(String,Int)]( ("zhangsan",20),("lisi",50),("wangwu",60))
val list11 = list10.map(x=> new Person(x._1,x._2))//List(对象一,对象二,对象三)
只压第二层
val list12 = List[List[String]] ( List("scala","python"),List("hadoop","flume","kafka") )
val list13 = list12.flatten////List("scala","python","hadoop","flume","kafka")
//string也属于Seq,可以被压平成字符
val list16 = List[String]("hello spark","hello scala")
val list17 = list16.flatten
println(list17) //List(h, e, l, l, o, , s, p, a, r, k, h, e, l, l, o, , s, c, a, l, a)
等价于先map,再flatten
val list16 = List[String]("hello python","hello scala","hadoop flume")
val list17 = list16.map(x=>x.split(" ")).flatten
println(list17)//List(hello, spark, hello, scala)
根据自定义的规则进行分组,分组后的结果是一个Map,key是分组的条件,value是一个List
val list = List(("Shenczhen", "zhagnsan", 20), ("guangzhou", "lisi", 10), ("Shenczhen", "wangwu", 30), ("Shenczhen", "zhaoliu", 20), ("chengdu", "wuqi", 10))
val map: Map[(String, Int), List[(String, String, Int)]] = list.groupBy(x => {
(x._1, x._3)
})
println(map) //Map((Shenczhen,30) -> List((Shenczhen,wangwu,30)),
//(chengdu,10) -> List((chengdu,wuqi,10)),
// (guangzhou,10) -> List((guangzhou,lisi,10)),...)
迭代计算,本次计算的结果作为下次计算的输出
sum默认给的是集合的第一个值,然后从第二个元素开始遍历
从左往右
val list1 = List(1, 2, 3, 4)
val s = list1.reduce((sum, x)=>sum+x)
println(s)
从左往右
sum默认给的是集合的第一个括号参数的值,然后从第一个元素开始遍历
val i = list1.fold(0)((sum,x)=>sum+x)
println(i)
println(i)
过滤,判断条件为True保留,返回过滤后的List集合
//找出集合中的偶数
val list1 = List(1, 2, 3, 4, 5)
val listfilter =list1.filter(x => {
x % 2 == 0
})
println(listfilter)//List(2, 4)
原文:https://www.cnblogs.com/wh984763176/p/13387659.html