58.scala编程思想笔记——序列
欢迎转载,转载请标明出处:http://blog.youkuaiyun.com/notbaron/article/details/50458701
源码下载连接请见第一篇笔记。
Vector是一种集合,可以在集合中存储事务。Vector还是一种序列,此外还有另一种基本序列,即List. 可以在不导入任何类的情况下使用它们,就像它们是语言中的固有类型一样。
Vector和List继承自Seq序列,因此具有公共的操作,所以testSeq方法在其上都可以运行。
例如:
import com.atomicscala.AtomicTest._
testSeq(Vector(1, 7, 22, 11, 17))
testSeq(List(1, 7, 22, 11, 17))
def testSeq(s:Seq[Int]) = {
// Is thereanything inside?
s.isEmpty isfalse
// How manyelements inside?
s.length is 5
// Appendingto the end:
s :+ 99 isSeq(1, 7, 22, 11, 17, 99)
// Insertingat the beginning:
47 +: s isSeq(47, 1, 7, 22, 11, 17)
// Get thefirst element:
s.head is 1
// Get therest after the first:
s.tail isSeq(7, 22, 11, 17)
// Get thelast element:
s.last is 17
// Get allelements after the 3rd:
s.drop(3) isSeq(11, 17)
// Get allelements except last 3:
s.dropRight(3) is Seq(1, 7)
// Get first3 elements:
s.take(3) isSeq(1, 7, 22)
// Get final3 elements:
s.takeRight(3) is Seq(22, 11, 17)
// Sectionfrom indices 2 up to 5:
s.slice(2,5)is Seq(22, 11, 17)
// Get valueat location 3:
s(3) is 11
// See if itcontains a value:
s.contains(22) is true
s.indexOf(22)is 2
// Replacevalue at location 3:
s.updated(3,16) is
Seq(1, 7,22, 16, 17)
// Removelocation 3:
s.patch(3,Nil, 1) is
Seq(1, 7,22, 17)
// Append twosequences:
val seq2 = s++ Seq(99, 88)
seq2 isSeq(1, 7, 22, 11, 17, 99, 88)
// Find theunique values and sort them:
s.distinct.sorted is
Seq(1, 7,11, 17, 22)
// Reversethe order:
s.reverse is
Seq(17, 11,22, 7, 1)
// Find thecommon elements:
s.intersect(seq2) is Seq(1,7,22,11,17)
// Smallestand largest values:
s.min is 1
s.max is 22
// Does itbegin or end
// with thesesequences?
s.startsWith(Seq(1,7)) is true
s.endsWith(Seq(11,17))is true
// Total allthe values:
s.sum is 58
// Multiplytogether all the values:
s.product is28798
//"Set" forces unique values:
s.toSet isSet(1, 17, 22, 7, 11)
}