1、Scala操作List
1.1 初始化List
scala> val list0 = List(9, 2, 8, 3, 4, 5, 6, 7)
list0: List[Int] = List(9, 2, 8, 3, 4, 5, 6, 7)
1.2 List过滤筛选
// 筛选偶数
scala> list0.filter(_ % 2 == 0)
res0: List[Int] = List(2, 8, 4, 6)
list0.filter(_ % 2 == 0) 等价于list0.filter(x => x % 2 == 0)
// 筛选偶数
scala> list0.filter(x => x % 2 == 0)
res1: List[Int] = List(2, 8, 4, 6)
// 筛选不是偶数
scala> list0.filterNot(x => x % 2 == 0)
res2: List[Int] = List(9, 3, 5, 7)
字符串列表过滤操作
// 初始化字符串元素类型的列表
scala> val list_str = List("Nice","To","Meet","You")
list_str: List[String] = List(Nice, To, Meet, You)
// 筛选N开头的
scala> val x = list_str.filter(x => x.startsWith("N"))
x: List[String] = List(Nice)
// 筛选o头的
scala> var y = list_str.filter(x => x.contains("o"))
y: List[String] = List(To, You)
// 筛选长度大于3的
scala> var z = list_str.filter(x => x.length()>3)
z: List[String] = List(Nice, Meet)
// 多次过滤:筛选长度大于3的 => 筛选N开头的
scala> var z = list_str.filter(x => x.length()>3).filter(x=> x.contains("N"))
list_str.filter(x => x.length()>3).filter(x=> x.contains(“N”)) // 多次过滤
1.2 map调用自定义函数
map调用自定义函数
// 自定义函数 => 所有数字 * 2
scala> def mutiple(n:Int):Int={
| 2*n
| }
mutiple: (n: Int)Int
scala> val list = List(3, 4, 5)
list: List[Int] = List(3, 4, 5)
// map方式调用自定义函数
scala> val list2 = list.map(mutiple)
list2: List[Int] = List(6, 8, 10)
1.3 flatMap方法
迭代器调用flatMap,flatMap对每个元素调用方法
// 初始化字符串类型的List
scala> val listStr01 = List("hello word", "hello hdfs", "hadoop hdfs")
listStr01: List[String] = List(hello word, hello hdfs, hadoop hdfs)
// 按空格拆分
scala> val listStr02 = listStr01.flatMap(_.split(" "))
listStr02: List[String] = List(hello, word, hello, hdfs, hadoop, hdfs)
flatMap 接 操作方法
1.4 foreach方法
// foreach遍历打印元素
scala> listStr02.foreach(println)
hello
word
hello
hdfs
hadoop
hdfs
2、Scala操作Array
2.1 初始化Array
scala> var d : Array[Int] = Array [ Int ] (1, 2, 3, 4, 5)
d: Array[Int] = Array(1, 2, 3, 4, 5)
2.2 ++操作符 增加元素
scala> d ++ Array [ Int ](6)
res15: Array[Int] = Array(1, 2, 3, 4, 5, 6)
2.3 toIterator迭代器
scala> d.toIterator
res17: Iterator[Int] = non-empty iterator
3、集合Set
3.1 创建集合
// 创建可变的集合
scala> var set = scala.collection.mutable.Set[String]()
set: scala.collection.mutable.Set[String] = Set()
mutable.Set是可变的,允许增加集合元素
3.2 集合添加元素
// 添加元素 写法1
scala> set += "A"
res24: scala.collection.mutable.Set[String] = Set(A)
scala> set += "B"
res27: scala.collection.mutable.Set[String] = Set(B, A)
// 添加元素 写法2
scala> set.add("C")
res28: Boolean = true
scala> set
res29: scala.collection.mutable.Set[String] = Set(B, C, A)
set += ‘A’ 等价于 set.add(“A”)