1 /** 2 * List基础操作 3 * Created by zhen on 2018/11/14. 4 */ 5 object ListDemo { 6 def main(args: Array[String]) { 7 val intList : List[Int] = List(1,3,5,6,7) 8 val list : List[String] = List("Spark","Hadoop","Scala","Tachyon") 9 // map 10 println(intList map (_ + 1)) // 遍历并执行操作,不修改原数据 11 println(intList) 12 println(list map (_.length)) // 求每个数据的长度 13 println(list map (_.toList.reverse.mkString))// 倒序 14 println(list map(_ toList)) 15 // flatMap 16 println(list flatMap(_ toList)) 17 // range 18 println(List.range(1,5)) 19 println(List.range(1,5) flatMap(i => List.range(1,i))) 20 println(List.range(1,5) flatMap(i => List.range(1,i) map(j => (i,j)))) 21 var sum = 0 22 List(1,2,3,4) foreach(sum += _) 23 println(sum) 24 // filter 25 println(List(1,2,3,4) filter(_ % 2 == 0)) 26 println(list filter(_.length == 5)) 27 // partition 数据拆分 28 println(intList partition(_ % 2 == 1)) 29 // find 返回满足条件的第一个元素 30 println(intList find(_ <= 3)) 31 // takeWhile 获取满足条件的数据 32 println(intList takeWhile(_ < 3)) 33 // dropWhile 获取不满足条件的数据 34 println(intList dropWhile(_ < 3)) 35 // span 数据拆分与partition功能类似 36 println(intList span(_ < 3)) 37 // exists 判断是否存在满足的数据 38 println(list exists(s => s contains "o")) 39 println(list exists(s => s contains "ha")) 40 } 41 }
结果: