1. 数组
object CH_0205_Arrays {
def main(args: Array[String]): Unit = {
//1.声明数组
val arr = Array[Int](1,4,5,0)
//2.访问数组元素
print(arr(0))
//3.修改数组中的元素
arr(0) = 10
println(arr(0))
//4.遍历数组
arr.foreach(println)
}
}
2. 链表
object CH_0206_List {
def main(args: Array[String]): Unit = {
//1.声明不可变链表
val list1 = List(1,2,8,37)
//2.遍历链表
list1.foreach(print)
//3.声明可变链表
val list02 = new ListBuffer[Int]()
//4.往可变链表中添加元素
list02.+=(29,10,391,20,10)
list02.foreach(println)
//5.删除可变链表中的元素
list02.-=(10)
list02.foreach(println)
}
}
- Set
object CH_0207_Set {
def main(args: Array[String]): Unit = {
//1.声明不可变Set
val set01 = Set[Int](11,9,10,289,10,20)
set01.foreach(println)
//2.声明可变Set
import scala.collection.mutable.Set
val set02 = Set(11,9,10,289,10)
set02.add(9999)
set02.foreach(println)
}
}
4.Tuple
object CH_0208_Tuple {
def main(args: Array[String]): Unit = {
//1.声明Tuple
val tp01 = Tuple2(89,"Hello")
val tp02 = Tuple3(190,"Great",189.90)
//2.访问Tuple中的元素
println(tp01._1)
println(tp02._1)
//3.迭代器遍历Tuple中的元素
val iterator = tp02.productIterator
while (iterator.hasNext){
println(iterator.next())
}
}
}
5.Map
object CH_0209_Map {
def main(args: Array[String]): Unit = {
//1.声明Map
val map = Map(("ID01", 190), "ID02" -> 120)
//2.获取Map中的存在的Key的值,返回的结果是Option,Option有两种类型,一个是Some,一个是None,若Key存在,则返回的是Some
val existKeyVal = map.get("ID01").get
println(existKeyVal)
//3.获取Map中的不存在的Key的值,返回的结果是Option,Option有两种类型,一个是Some,一个是None,若Key不存在,则返回的是None,取数据时会报错
val noExistKeyVal = map.get("ID03").get
println(noExistKeyVal)
//4.使用getOrElse访问key的值
val getVal = map.get("ID01").getOrElse(200)
println(getVal)
//5.遍历map中所有key的值
for (elem <- map) {
println(s"key: ${elem._1}, value: ${elem._2}")
}
}
}
6.map
object CH_0209_Map {
def main(args: Array[String]): Unit = {
val list = List(9, 10, 28)
val listMap = list.map((x: Int) => {
x * 10
})
listMap.foreach(println)
}
}
- flatMap
object CH_0210_FlatMap {
def main(args: Array[String]): Unit = {
val listStr = List("Hello World","Great Job","Hello Job")
//flatMap接收原有集合中每个词组并拆分成独立的单词生成新的集合,但随着数据量增大,内存空间会不断膨胀,使用迭代器模式解决此问题
val listStrFlatMap = listStr.flatMap((str: String) => {
str.split(" ")
})
listStrFlatMap.foreach(println)
}
}
8.迭代器
object CH_0212_Iterator {
def main(args: Array[String]): Unit = {
val listStr = List("Hello World","Great Job","Hello Job")
//使用迭代器的好处就是保证原有的数据集不改变,且中间的加工过程是不保存数据
val iterator = listStr.iterator
val flatMapItr = iterator.flatMap((str: String) => {
str.split(" ")
})
val mapItr = flatMapItr.map((_, 1))
mapItr.foreach((println))
}
}
标签:03,String,val,10,println,foreach,集合,Array
From: https://www.cnblogs.com/crispy-bro/p/18322636