基础代码:
1 //创建一个List 2 val lst0 = List(1,7,9,8,0,3,5,4,6,2) 3 //将lst0中每个元素乘以10后生成一个新的集合 4 val lst1 = lst0.map(_*10) 5 println(lst1) 6 7 //将lst0中的偶数取出来生成一个新的集合 8 val lst2 = lst0.filter(_%2 ==0) 9 10 //将lst0排序后生成一个新的集合 11 val lst3 = lst0.sorted 12 13 //反转顺序 14 val lst4 = lst0.sorted.reverse 15 16 //将lst0中的元素4个一组,类型为Iterator[List[Int]] 17 val lst5 = lst0.grouped(4) 18 19 //将Iterator转换成List 20 val lst6 = lst5.toList 21 22 //将多个list压扁成一个List 23 val lst7 = lst6.flatten 24 25 val lines = List("hello tom hello jerry", "hello jerry", "hello kitty") 26 //先按空格切分,在压平 27 val lst8= lines.map(_.split(" ")).flatten 28 29 30 //并行计算求和 31 val lst9 =lst0.par.reduce(_+_) 32 val lst10 = lst0.par.fold(0)(_+_) 33 34 //化简:reduce 35 //将非特定顺序的二元操作应用到所有元素 36 val lst11= lst0.fold(0)(_+_) 37 //安装特点的顺序 38 val lst12= lst0.foldLeft(0)(_+_) 39 40 41 //折叠:有初始值(无特定顺序) 42 val lst13 = lst0.par.fold(10)(_+_) 43 val lst14 = lst0.fold(10)((x,y ) => x+y) 44 45 //折叠:有初始值(有特定顺序) 46 val lst15 = lst0.par.foldLeft(10)(_+_) 47 val lst16 = lst0.foldLeft(10)((x,y)=>x+y) 48 49 50 //聚合 51 val arr = List(List(1, 2, 3), List(3, 4, 5), List(2), List(0)) 52 53 //聚合操作, _+_.sum 初始值+集合中第一个元素的sum 54 // _+_ 各个元素的sum,依次相加求和 55 val i = arr.aggregate(0)(_+_.sum,_+_) 56 57 58 val l1 = List(5,6,4,7) 59 val l2 = List(1,2,3,4) 60 //求并集 61 val ls0 = l1.union(l2) 62 63 //求交集 64 val ls1 = l1.intersect(l2) 65 66 //求差集 67 val ls2 = l1.diff(l2) 68 69 70 val lines = List("hello tom hello jerry", "hello jerry", "hello kitty") 71 72 //wordcount 73 74 lines.flatMap(_.split(" ")).map((_, 1)).groupBy(_._1).mapValues(_.foldLeft(0)(_+_._2)) 75 lines.flatMap(_.split(" ")).map((_, 1)).groupBy(_._1).map(t=>(t._1, t._2.size)).toList.sortBy(_._2).reverse