object ListTest {
def main(args: Array[String]): Unit = {
//创建一个List
val list0=List(1,7,9,8,0,3,5,4,6,2)
//1 将list0中的每一个元素乘以10后生成一个新的集合
val list1=list0.map(_*10)
println("list1==== "+list1)
//2将list0中的偶数取出来生成一个新的集合
val list2=list0.filter(_%2==0)
println("list2==== "+list2)
//3. 排序
val list3: List[Int] = list0.sorted
val list4: List[Int] = list0.sortBy(x => x)
val sortWith: List[Int] = list0.sortWith(_>_)
println(list3)
println(list4)
println("降序______________"+sortWith)
//4. 反转
val reverse: List[Int] = list3.reverse
println("反转" + reverse)
//5. 分组
val list7: Iterator[List[Int]] = list0.grouped(4)
println("list7==== "+list7)
/*for (i <- list7){
println(i)
}*/
//将Iterator转换成List
val list8=list7.toList
println("list8==== "+list8)
//9. 多个list压平, 也就是抽取出来
val list9: List[Int] = list8.flatten
println("list9---" + list9)
val lines = List("hello tom hello jerry", "hello jerry", "hello kitty")
//先按空格切分,在压平
val result1: List[String] = lines.flatMap(_.split(" "))
println(result1)
//并行计算求和
val sum: Int = list0.par.sum
println(sum)
//reduce 计算
val sumReduce: Int = list0.reduce(_+_)
println("sumReduce===="+sumReduce)
//有特定顺序
val left: Int = list0.reduceLeft(_+_)
val right: Int = list0.reduceRight(_+_)
println(left)
println(right)
//折叠
val fold: Int = list0.fold(100)(_+_)
println("fold=="+fold)
//聚合
val list10= List(List(1, 2, 3), List(4, 5, 6), List(7,8), List(9,0))
val par: ParSeq[List[Int]] = list10.par
println("par--------------"+par)
val aggregate: Int = par.aggregate(10)(_+_.sum,_+_)
println(aggregate)
//获取到参与并行计算的线程
println(list10.par.collect{
case _=>Thread.currentThread().getName
}.distinct)
val l1 = List(5,6,4,7)
val l2 = List(1,2,3,4)
//求并集
val union: List[Int] = l1.union(l2)
val intersect: List[Int] = l1.intersect(l2)
println(union)
println(intersect)
//求差集
val r3=l1.diff(l2)
println("r3=== "+r3)
}
}
Scala常用算子原理及代码实现
最新推荐文章于 2022-11-11 11:52:26 发布