scala学习笔记(2)

scala学习笔记

#集合有三大类:seq(序列),set(集合),map(映射)
不可变 seq
val list1 =List(1,2,3)
val list2 = 0::list1
val list3 list1.::(0)
val list4 = 0 +: list1
val list5 = list1.+:(0)
val list6 = list1 :+ 4
val list7 = List(5,6,7)
val list8 = list1 + list7
import scala.collection.ListBuffer
val list9 = ListBuffer(1,2,3)
val list10 = ListBuffer(4,5,6)

#不可变set
import scala.collection.immutable.HashSet

val set1 = new HashSet[Int]
val set2 = set1 + 1
set1
set2

val set3 = set2 ++ Set(2,3,4)
set 3

#可变set
import scala.collection.mutable.HashSet

val set1 = new HashSetInt
set1 += 1
set1

set1 += 2
set1

set1.add(3)

set1

set1 ++ Set(4,5,6)
set1

set1 ++= Set(5,6,7) #去重

set1 -= 1 #删除数据

set1.remove(2)

#集合Map
import scala.collection.mutable._
val map1 = new HashMapString,Int
map1(“scala”) = 1
map1

map1 += ((“java”,2))

map1 += ((“python”,3),(“C#”,4))

map1
map1.put(“C++”,5)

map1

map1.remove(“C#”)

//创建一个List
val list0 = List(2, 5, 9, 6, 7, 1, 8, 3, 4, 0)

//将list0 中每个元素乘以2后生成一个新的集合
val list1 = list0.map(_ * 2)
//将list0 中的偶数取出来生成一个新的集合
val list2 = list0.filter(_ % 2 == 0)
//将list0排序生成一个新的集合
val list3 = list0.sorted
//将list3排序后反转生成一个新的集合
val list4 = list3.reverse
//将list0中的元素4个一组,类型为Iterator[list[Int]]
val it = list0.grouped(4)
//println(it.toBuffer)
//将Iterator[list[Int]]转换成list
val list5 = it.toList
//将多个list压扁成一个list
val list6 = list5.flatten
//先按空格切分,再压平
val lines = List("hello java hello scala hell python")
// val words = lines.map(_.split(" "))
//val flatterwords = words.flatten
val result = lines.flatMap(_.split(" "))
//并行计算求和&并发计算求和
val arr = Array(1,2,3,4,5,6,7,8,9,10)
//val res = arr.par.sum
//和线程有关,每个线程计算一部分,(1+2+3+4)+(5+6+7)+(8+9)


//按照特定的顺序进行聚合
//(((1+2)+3)+4)+5
//val res = arr.reduce(_+_)     //arr.reduceLeft(_+_)同样的结果

//折叠:有初始值(无特定顺序)
//val res = arr.par.fold(10)(_+_)

//折叠:有初始值(有特定顺序)
val res = arr.foldLeft(10)(_+_)
println(res)

//聚合
val list1 = List(List(1,2,3),List(3,4,5),List(2),List(0))
val res = List1.flatten.reduce(+)

val res = List1.aggregate(0)(+.sum,+)

val l1 = List(5,6.4,7)
val l2 = List(1,2,3,4)
//並集

val res = l1 union l2

//交集
val res = l1 intersect l2

//差集
val res = l1 diff l2

你可能感兴趣的:(scala)