Today, let's learn how to use a for expression to make a query in Scala.
Let's take a look at the sample code
Case Class Book (title:string,authors:list[string])
Object text_87 {def main (args:array[string]) {
Val Books:list[book] = List (
Book ("Scala Programming", List ("Zhangbanner", "Dongxicheng", "Wangjialin")),
Book ("Quick Scala", List ("Shiming", "Xuyangkai")),
Book ("Spark Programming", List ("Wangjialin", "Wangjiahu")),
Book ("Hadoop Learning", List ("Dongxicheng", "Chenchao"))
)
Val result = for (b<-books;a<-b.authors if a startsWith "Dongxicheng") yield b.title
println (Result)
Val result2 = for (b <-Books if (B.title indexOf "Programming") >= 0) yield B.title
println (RESULT2)
}
}
First, we define a case class book about books.
Then, use case class to create a book library books, which is a list, each of which is a book and the properties of the book.
Then we start using the for expression to start the query.
First, the first query, through the generator, facilitates all the books of the books list, then uses another generator to traverse the list of authors of each book, establishes a guard, takes out a book that matches the author's name, and, finally, forms a list of the titles of the eligible books.
Take a look at the second query, find the title containing the programming book, and the name of the book to form a new list.
Share more of the Scala resources:
Baidu Cloud Disk: http://pan.baidu.com/s/1gd7133t
Micro Cloud Disk: http://share.weiyun.com/047efd6cc76d6c0cb21605cfaa88c416
360 Cloud Disk: Http://yunpan.cn/cQN9gvcKXe26M (extract code: 13CD)
Information from DT Big Data Dream Factory public account: Dt_spark
Follow the account for more information about Scala learning
87th: Use the for expression in Scala for queries