/**
* List基础操作
* Created by zhen on 2018/11/14.
*/
object ListDemo {
def main(args: Array[String]) {
val intList : List[Int] = List(1,3,5,6,7)
val list : List[String] = List("Spark","Hadoop","Scala","Tachyon")
// map
println(intList map (_ + 1)) // 遍历并执行操作,不修改原数据
println(intList)
println(list map (_.length)) // 求每个数据的长度
println(list map (_.toList.reverse.mkString))// 倒序
println(list map(_ toList))
// flatMap
println(list flatMap(_ toList))
// range
println(List.range(1,5))
println(List.range(1,5) flatMap(i => List.range(1,i)))
println(List.range(1,5) flatMap(i => List.range(1,i) map(j => (i,j))))
var sum = 0
List(1,2,3,4) foreach(sum += _)
println(sum)
// filter
println(List(1,2,3,4) filter(_ % 2 == 0))
println(list filter(_.length == 5))
// partition 数据拆分
println(intList partition(_ % 2 == 1))
// find 返回满足条件的第一个元素
println(intList find(_ <= 3))
// takeWhile 获取满足条件的数据
println(intList takeWhile(_ < 3))
// dropWhile 获取不满足条件的数据
println(intList dropWhile(_ < 3))
// span 数据拆分与partition功能类似
println(intList span(_ < 3))
// exists 判断是否存在满足的数据
println(list exists(s => s contains "o"))
println(list exists(s => s contains "ha"))
}
}
结果: