当前位置:网站首页>Scala basic tutorial -- 17 -- Collection
Scala basic tutorial -- 17 -- Collection
2022-07-04 18:53:00 【Empty.】
Scala Basic course –17– aggregate
Chapter goal
- Understand the related concepts of sets
- master Traversable Use of sets
- Master random student sequence cases
1. aggregate
1.1 summary
Anyone who knows programming knows Program = Algorithm + data structure this sentence , It was developed by the famous Swiss computer scientist Nicholas · wo Bring up the , And so is he 1984 Turing Award winner . Algorithm refers to a series of effective calculations , Common steps . Algorithm and data structure are two complementary aspects in program design , Therefore, data structure is also a very important aspect of programming . Many programming languages provide corresponding programming libraries of data structures ,
And call it a collection library (Collection Library). Scala There is also a collection library , Its advantages are as follows :
Easy to use
Use the 20 To 50 There are about two ways , Flexible combination , Can solve most set problems .
concise
A simple word ( for example : foreach), One or more loop operations can be realized .
Security
Most errors can be found at compile time .
Fast
When implementing methods of collection type , Have been tuned , Users can choose the appropriate set according to their needs .
Unified
Scala The collection of has a very rigorous inheritance system , Collections of similar types have the same set of methods , And their own unique methods .
1.2 classification
Scala Support at the same time Immutable sets and variable sets , Because immutable sets can be accessed safely and concurrently , So it is also the default collection class library . stay Scala in , For almost all collection classes , Both are available in variable and immutable versions , As follows :
Immutable set : refer to
Once the initialization of the elements in the collection is completed, they cannot be changed , Any change to the set will generate a new set .All in
scala.collection.immutableUnder this bag , When using There is no need to guide the package manually .Variable set : refer to
The set itself can change dynamically , And variable sets provide a way to change the elements in the setAll in
scala.collection.mutableUnder this bag , Use yes You need to guide the package manually .
Here's the picture :

Tips :
Variable sets are richer than immutable sets .
for example : stay Seq Collection , Added Buffer aggregate , We often use : ArrayBuffer and ListBuffer.
When we come into contact with a new inheritance system , The proposal USES
Top level of learning , Use the bottom layerThe way .
The top level defines what is common to the entire inheritance system .
And the bottom layer is the concrete embodiment , Realization .
2. Traversable
2.1 summary
Traversable It's a trait (trait), It is the parent of other sets , Its sub characteristics immutable.Traversable and mutable.Traversable They are the parents of immutable sets and variable sets , Most common methods in collections are defined in this trait . Therefore, understanding its function is very important for learning other collection classes .
2.2 Format
Format 1 : Create empty Traversable object .
// Mode one : adopt empty Method realization . val t1 = Traversable.empty[Int] // Mode two : Through parentheses val t2 = Traversable[Int]() // Mode three : adopt Nil Realization . val t3 = NilFormat two : Create an... With parameters Traversable object .
// Mode one : adopt toTraversable() Method realization val t1 = List(1, 2, 3).toTraversable // Mode two : adopt Traversable Of the accompanying objects of apply() Method realization . val t1 = Traversable(1, 2, 3)
2.3 Example 1 : establish Traversable object
- Create empty , Used to store Int Of type data Traversable object .
- establish Traversable A collection of objects , Store numbers 1, 2, 3, And print the results to the console .
Reference code
// Case study : Demonstrate creating Traversable object .
object ClassDemo01 {
def main(args: Array[String]): Unit = {
//1. Create empty , Used to store Int Of type data Traversable object .
//1.1 Create objects .
val t1: Traversable[Int] = Traversable.empty[Int]
val t2: Traversable[Int] = Traversable[Int]()
val t3: Traversable[Int] = Nil
//1.2 Compare them for equality .
println(t1 == t2) //== Compare the data in the set .
println(t1 == t3)
println(t2 == t3)
println(t1 eq t2) //eq The comparison is the address value of the set .
println(t1 eq t3)
println(t2 eq t3)
println("-" * 15)
//2. establish Traversable A collection of objects , Store numbers 1, 2, 3, And print the results to the console .
//2.1 adopt toTraversable() Method realization .
val t4: Traversable[Int] = List(1, 2, 3).toTraversable
val t5: Traversable[Int] = Set(1, 2, 3).toTraversable
//2. adopt Traversable Of the accompanying objects of apply() Method realization .
val t6:Traversable[Int] = Traversable(11, 22, 33, 44, 55)
//3. Print the results ( because Traversable It's the quality , So the bottom layer is implemented through its specific subclasses ).
println(s"t4: ${
t4}")
println(s"t5: ${
t5}")
println(s"t6: ${
t6}")
}
}
2.4 Case 2 : Transposition Traversable aggregate
Students who have known linear algebra know , Matrix has a transpose operation , stay Scala in , Can pass transpose() Method To achieve similar operations .
Here's the picture :

Be careful :
When transposing , The program will automatically detect whether the number of elements in each set is consistent , If the same , Then the transpose succeeds . If it's not consistent , False report .
demand
- Define a Traversable aggregate t1, It has three elements , Every element is Traversable aggregate , And store the following data respectively :
- The first element stores (1, 4, 7), The second element stores (2, 5, 8), The third element stores (3, 6, 9).
- adopt transpose Method , The collection t1 Do transpose .
- Print the results .
Reference code
// Case study : Demonstrate transpose set .
object ClassDemo02 {
def main(args: Array[String]): Unit = {
//1. Define a Traversable aggregate t1, It has three elements , Every element is Traversable aggregate , And store the following data respectively :
//2. The first element stores (1, 4, 7), The second element stores (2, 5, 8), The third element stores (3, 6, 9).
val t1 = Traversable(Traversable(1, 4, 7), Traversable(2, 5, 8), Traversable(3, 6, 9))
//3. adopt transpose Method , The collection t1 Do transpose .
val t2 = t1.transpose
//4. Print the results .
println(t2)
}
}
2.5 Case three : Splice set
In actual development , Data is obtained from multiple channels , So we often need to splice some data , stay Scala in , We can go through ++ To splice data , But this method will create a large number of temporary collections ( namely : Every time ++ once , A new temporary set will be created ), In this case , We can go through concat() Method To achieve . This method will calculate the size of the required set in advance , Then generate a set , Reduce useless temporary collections in the middle , So it's more effective .
demand
- There are three known Traversable aggregate , Store separately (11, 22, 33), (44, 55), (66, 77, 88, 99) Elements .
- adopt concat() Method to splice the above three sets .
- Print the spliced results to the console .
Reference code
// Case study : demonstration concat() Method , Splice set .
object ClassDemo03 {
def main(args: Array[String]): Unit = {
//1. There are three known Traversable aggregate , Store separately (11, 22, 33), (44, 55), (66, 77, 88, 99) Elements .
val t1 = Traversable(11, 22, 33)
val t2 = Traversable(44, 55)
val t3 = Traversable(66, 77, 88, 99)
//2. adopt concat() Method to splice the above three sets .
val t4 = Traversable.concat(t1, t2, t3)
//3. Print the spliced results to the console .
println(s" The result after splicing is : ${
t4}")
}
}
2.6 Case four : Screening elements by partial function
stay Scala in , We can also go through collect() Method Realization Partial function associative set To use , To filter the specified data from the set .
Format
def collect[B](pf: PartialFunction[A, B]): Traversable[B]
explain :
[B]After partial function processing , The data type of the return value .pf: PartialFunction[A, B]Express collect() Method needs to pass in a partial function object .Traversable[B]Represents a collection of returned concrete data .
demand
- There is a known Traversable aggregate , The storage element is : 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.
- adopt collect Method to filter out all even numbers in the set .
Reference code
// Case study : Filter out all even numbers in the set through partial function .
object ClassDemo04 {
def main(args: Array[String]): Unit = {
//1. There is a known Traversable aggregate , The storage element is : 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.
val t1 = (1 to 10).toTraversable
//2. adopt collect Method to filter out all even numbers in the set .
val t2 = t1.collect( {
case x if x % 2 == 0 => x
})
//3. Print the results .
println(t2)
}
}
2.7 Case 5 : Calculate the factorial of set elements
Suppose a Traversable[Int] The collection contains (1, 2, 3, 4, 5) Five numbers , If we calculate the factorial of each element , And put it in a new Traversable[Int] Collection , We can do it by returning , But this implementation has drawbacks , Every calculation starts from scratch , for example : obtain 5 The factorial , It's through 5 * 4 * 3 * 2 * 1 Calculated , Did not use the previous calculation 4 The result of the factorial of . here , We can go through scan() Method To optimize this requirement , It not only puts the intermediate calculation results into a new set , And the intermediate result will be passed to the next function call .
Format
def scan[B](z: B)(op: (B, B) => B)
explain :
[B]Represents the data type of the return value .(z: B)Represents the initialization value .(op: (B, B) => B)Represents a specific operation function .- scan() Method is equivalent to scanLeft() Method , There is another method opposite to it scanRight().
demand
- Definition Traversable aggregate t1, Storage 1, 2, 3, 4, 5 These five numbers .
- Suppose the initial value is 1, adopt scan() Method , Get separately t1 The factorial value of each element in the set .
- Print the results .
Reference code
// Case study : adopt scan() Method , Get the factorial value of the element in the collection .
object ClassDemo05 {
def main(args: Array[String]): Unit = {
//1. Definition Traversable aggregate t1, Storage 1, 2, 3, 4, 5 These five numbers .
val t1 = Traversable(1, 2, 3, 4, 5)
//2. Suppose the initial value is 1, adopt scan() Method , Get separately t1 The factorial value of each element in the set .
val t2 = t1.scan(1)(_ * _)
//3. Print the results .
println(t2)
}
}
2.8 Case 6 : Get the specified element of the collection
Collections are used to store data , Since it can store , Then we can certainly get the data we want from the set , It can be achieved by the following methods :
head: Get the first element of the collection , If the element does not exist , Throw out
NoSuchElementException abnormal.last: Get the last element of the collection , If the element does not exist , Throw out
NoSuchElementException abnormal.headOption: Get the first element of the collection , The return value type is Option.
lastOption: Get the last element of the collection , The return value type is Option.
find: Find the first element in the set that meets the specified condition .
slice: Intercept some elements in the set .
def slice(from:Int, until: Int): Traversable[A]Be careful :
Interception from from( Starting index ) Start , to until Indexes ( End index ) The ending element , contain from Indexes , But it doesn't include until Indexes .
demand
- Define a Traversable aggregate , contain 1, 2, 3, 4, 5, 6 These six elements .
- Pass respectively head, headOption, last, lastOption Get the first and last element in the collection , And print .
- adopt find Method to get the first even number in the collection , And print .
- adopt slice() Method to get 3, 4, 5 These three elements , And put them in a new Traversable Collection , Then print the results .
Reference code
// Case study : obtain Traversable Object specific elements
object ClassDemo06 {
def main(args: Array[String]): Unit = {
//1. Define a Traversable aggregate , contain 1, 2, 3, 4, 5, 6 These six elements .
val t1 = (1 to 6).toTraversable
//2. Pass respectively head, headOption, last, lastOption Get the first and last element in the collection , And print .
println(t1.head)
println(t1.last)
println(t1.headOption)
println(t1.lastOption)
//3. adopt find Method to get the first even number in the collection , And print .
println(t1.find(_ % 2 == 0))
//4. adopt slice() Method to get 3, 4, 5 These three elements , Then print the results .
val t2 = t1.slice(2, 5)
println(t2)
}
}
2.9 Case seven : Determine whether the element is legal
If we meet Judge whether all elements in the set meet the specified conditions , Or any element meets the specified conditions This kind of demand , You can consider using it forall() Methods and exists() Method To implement the .
forall(): Returns... If all elements in the collection meet the specified conditions true, Otherwise return to false.
def forall(p: (A) => Boolean): Booleanexist(): As long as any element in the collection meets the specified conditions, it returns true, Otherwise return to false.
def exists(p: (A) => Boolean): Boolean
demand
- Definition Traversable aggregate t1, contain 1 To 6 These six numbers .
- adopt forall() Method realization , Judge t1 Whether the elements in are all even .
- adopt exists() Method realization , Judge t1 Is there an even number in .
Reference code
// Case study : Determine whether the element is legal
object ClassDemo07 {
def main(args: Array[String]): Unit = {
//1. Definition Traversable aggregate t1, contain 1 To 6 These six numbers .
val t1 = (1 to 6).toTraversable
//2. adopt forall() Method realization , Judge t1 Whether the elements in are all even .
println(t1.forall(_ % 2 == 0)) // All elements must meet the conditions .
//3. adopt exists() Method realization , Judge t1 Is there an even number in .
println(t1.exists(_ % 2 == 0)) // As long as one element meets the condition .
}
}
2.10 Case eight : Aggregate functions
If we want to Count the number of elements in the set that meet the conditions , Or calculate the set elements and , The product of , For maximum , Minimum value, etc , You can use the following methods :
count: Count the number of elements in the set that meet the conditions .
def count(p: (A) => Boolean): Intsum: Get all the elements in the collection and .
product: Get the product of all elements in the set .
max: Get the maximum value of all elements in the collection .
min: Get the minimum value of all elements in the collection .
demand
- Definition Traversable aggregate t1, contain 1 To 6 These six numbers .
- adopt count() Methods statistics t1 The number of all odd numbers in the set , And print the results .
- adopt sum() Method to get t1 All elements in the set and , And print the results .
- adopt product() Method to get t1 The product of all elements in the set , And print the results .
- adopt max() Method to get t1 The maximum value of all elements in the set , And print the results .
- adopt min() Method to get t1 The minimum value of all elements in the set , And print the results .
Reference code
// Case study : Demonstrate aggregation operations .
object ClassDemo08 {
def main(args: Array[String]): Unit = {
//1. Definition Traversable aggregate t1, contain 1 To 6 These six numbers .
val t1 = (1 to 6).toTraversable
//2. adopt count() Methods statistics t1 The number of all odd numbers in the set , And print the results .
println(t1.count(_ % 2 == 0))
println(t1.filter(_ % 2 == 0).size) // It is not recommended to use , Because it will produce a new Traversable object .
//3. adopt sum() Method to get t1 All elements in the set and , And print the results .
println(t1.sum)
//4. adopt product() Method to get t1 The product of all elements in the set , And print the results .
println(t1.product)
//5. adopt max() Method to get t1 The maximum value of all elements in the set , And print the results .
println(t1.max)
//6. adopt min() Method to get t1 The minimum value of all elements in the set , And print the results .
println(t1.min)
}
}
2.11 Case nine : Set type conversion
occasionally , We need to Traversable Set into other sets to operate , It's time to use toXxx() Method 了 .
Be careful : Aforementioned Xxx Represents the name of the target set , for example : toList, toSet, toArray, toSeq wait …
demand
- Definition Traversable aggregate t1, contain 1 To 5 These five numbers .
- take t1 Sets are converted into arrays (Array), list (List), Set (Set) These three forms , And print the results .
Reference code
// Case study : Set type conversion .
object ClassDemo09 {
def main(args: Array[String]): Unit = {
//1. Definition Traversable aggregate t1, contain 1 To 5 These five numbers .
val t1 = (1 to 5).toTraversable
//2. take t1 Sets are converted into arrays (Array), list (List), Set (Set) These three forms , And print the results .
val arr = t1.toArray
val list = t1.toList
val set = t1.toSet
//3. Print the results .
println(arr)
println(list)
println(set)
}
}
2.12 Case 10 : Fill element
If we need to quickly add the same elements to the set , for example : Generate 5 All of them are "abc" Of Traversable object , It needs to be used fill() and iterate() The method , If you want to generate queue elements with specified intervals , You can go through range() Method To implement the , As follows :
- fill() Method : Quickly generate a specified number of elements .
- iterate() Method : According to the specified conditions , Generate the specified number of elements .
- range() Method : Generate all data of a specified interval in a certain interval .
demand
adopt fill() Method , Generate a Traversable aggregate , This collection contains 5 Elements , Values are " Spreading wisdom Podcast ".
adopt fill() Method , Generate a Traversable aggregate , This collection contains 3 A random number .
adopt fill() Method , Generate a Traversable aggregate , The format is as follows :
List(List( Spreading wisdom Podcast , Spreading wisdom Podcast ), List( Spreading wisdom Podcast , Spreading wisdom Podcast ), List( Spreading wisdom Podcast , Spreading wisdom Podcast ), List( Spreading wisdom Podcast , Spreading wisdom Podcast ), List( Spreading wisdom Podcast , Spreading wisdom Podcast ))adopt iterate() Method , Generate a Traversable aggregate , This collection contains 5 Elements , Respectively :1, 10, 100, 1000, 10000.
adopt range() Method , Get from number 1 Start , Cut off number 21 Between , The interval is 5 All data for .
Reference code
import scala.util.Random
// Case study : Demonstrate fill elements .
object ClassDemo10 {
def main(args: Array[String]): Unit = {
//1. adopt fill() Method , Generate a Traversable aggregate , This collection contains 5 Elements , Values are " Spreading wisdom Podcast ".
println(Traversable.fill(5)(" Spreading wisdom Podcast "))
//2. adopt fill() Method , Generate a Traversable aggregate , This collection contains 3 A random number .
println(Traversable.fill(5)(Random.nextInt(100)))
//3. adopt fill() Method , Generate a Traversable aggregate , There are 5 individual Traversable aggregate , Every Traversable The set has two elements .
//5 Express 5 individual Traversable, 2 Represent each Traversable There are 2 Elements .
println(Traversable.fill(5, 2)(" Spreading wisdom Podcast "))
//4. adopt iterate() Method , Generate a Traversable aggregate , This collection contains 5 Elements , Respectively :1, 10, 100, 1000, 10000.
//1 Represents the initialization value , 5 Indicates the number of elements to be finally obtained
println(Traversable.iterate(1, 5)(_ * 10))
//5. adopt range() Method , Get from number 1 Start , Cut off number 21 Between , The interval is 5 All data for .
println(Traversable.range(1, 21, 5)) // from 1 Start , By the end of 20, interval 5 All data for
println(Traversable.range(1, 5)) // from 1 Start , By the end of 5, interval 1 All data for ( If you don't specify , The default interval is 1)
}
}
3. Case study : Random student sequence
3.1 demand
- Define a Traversable aggregate , contain 5 A student ( The attribute is : full name , Age ) Information about , And the student's name and age information are randomly generated .
- Suppose the name information is (“ Zhang San ”, “ Li Si ”, “ Wang Wu ”, “ Zhao Liu ”, “ Panax notoginseng ”), The value range of age is : [20, 30), Front closed and back open writing .
- In descending order according to the age information of students , Print the results to the console .
3.2 Purpose
Investigate Sample class , random number , aggregate Related content .
3.3 step
- establish Student Sample class , The attribute is : full name , Age , Used to record student information .
- Definition list , Record the student's name information , The value is : “ Zhang San ”, “ Li Si ”, “ Wang Wu ”, “ Zhao Liu ”, “ Panax notoginseng ”.
- Create random number object r, It is used to obtain some random values .
- establish Traversable aggregate , contain 5 A random student information .
- take Traversable Set to List list .
- Through the list of sortWith() Method , In descending order of students' age .
- Print the results .
3.4 Reference code
import scala.util.Random
// Case study : Random student sequence
object ClassDemo11 {
//1. establish Student Sample class , The attribute is : full name , Age , Used to record student information .
case class Student(name:String, age:Int)
def main(args: Array[String]): Unit = {
//2. Definition list , Record the student's name information , The value is : " Zhang San ", " Li Si ", " Wang Wu ", " Zhao Liu ", " Panax notoginseng ".
val names: List[String] = List(" Zhang San ", " Li Si ", " Wang Wu ", " Zhao Liu ", " Panax notoginseng ")
//3. Create random number object r, It is used to obtain some random values .
val r: Random = new Random()
//4. establish Traversable aggregate , contain 5 A random student information .
val t1: Traversable[Student] = Traversable.fill(5)(Student(names(r.nextInt(names.size)), 20 + r.nextInt(10)))
//5. take Traversable Set to List list .
val t2: List[Student] = t1.toList
//6. Through the list of sortWith() Method , In descending order of students' age .
// The following two sorting methods are ok .
//val t3 = t2.sortBy(_.age).reverse
val t3 = t2.sortWith(_.age > _.age)
//7. Print the results .
println(t3)
}
}
", " Li Si ", " Wang Wu ", " Zhao Liu ", " Panax notoginseng ".
val names: List[String] = List(" Zhang San ", " Li Si ", " Wang Wu ", " Zhao Liu ", " Panax notoginseng ")
//3. Create random number object r, It is used to obtain some random values .
val r: Random = new Random()
//4. establish Traversable aggregate , contain 5 A random student information .
val t1: Traversable[Student] = Traversable.fill(5)(Student(names(r.nextInt(names.size)), 20 + r.nextInt(10)))
//5. take Traversable Set to List list .
val t2: List[Student] = t1.toList
//6. Through the list of sortWith() Method , In descending order of students' age .
// The following two sorting methods are ok .
//val t3 = t2.sortBy(_.age).reverse
val t3 = t2.sortWith(_.age > _.age)
//7. Print the results .
println(t3)
}
}
边栏推荐
- Improve the accuracy of 3D reconstruction of complex scenes | segmentation of UAV Remote Sensing Images Based on paddleseg
- Li Kou brush question diary /day5/2022.6.27
- What types of Thawte wildcard SSL certificates provide
- Li Kou brush question diary /day7/6.30
- [system disk back to U disk] record the operation of system disk back to U disk
- The controversial line of energy replenishment: will fast charging lead to reunification?
- ESP32-C3入门教程 问题篇⑫——undefined reference to rom_temp_to_power, in function phy_get_romfunc_addr
- .NET ORM框架HiSql实战-第二章-使用Hisql实现菜单管理(增删改查)
- 6.26CF模拟赛E:价格最大化题解
- PB的扩展DLL开发(超级篇)(七)
猜你喜欢

Li Kou brush question diary /day6/6.28

78 year old professor Huake impacts the IPO, and Fengnian capital is expected to reap dozens of times the return

Angry bird design based on unity

Li Kou brush question diary /day5/2022.6.27

【2022年江西省研究生数学建模】冰壶运动 思路分析及代码实现

Weima, which is going to be listed, still can't give Baidu confidence

Digital "new" operation and maintenance of energy industry

What types of Thawte wildcard SSL certificates provide

mysql5.7安装教程图文详解
![[2022 Jiangxi graduate mathematical modeling] curling movement idea analysis and code implementation](/img/63/8d5f875b4409511628faf2914836d3.png)
[2022 Jiangxi graduate mathematical modeling] curling movement idea analysis and code implementation
随机推荐
Grain Mall (I)
uni-app与uviewUI实现仿小米商城app(附源码)
网上开户安全吗?是真的吗?
Thawte通配符SSL证书提供的类型有哪些
Detailed explanation of the maturity classification of ITSS operation and maintenance capability | one article clarifies the ITSS certificate
PB的扩展DLL开发(超级篇)(七)
Weima, which is going to be listed, still can't give Baidu confidence
【Go语言刷题篇】Go完结篇|函数、结构体、接口、错误入门学习
TorchDrug教程
Neglected problem: test environment configuration management
基于NCF的多模块协同实例
【211】go 处理excel的库的详细文档
力扣刷题日记/day7/6.30
怎么开户才是安全的,
Android uses sqliteopenhelper to flash back
基于C语言的菜鸟驿站管理系统
Principle and application of ThreadLocal
中国农科院基因组所汪鸿儒课题组诚邀加入
Scala基础教程--15--递归
How is the entered query SQL statement executed?