1 package chapter07
2
3 object Test14_HighLevelFunction_Map {
4 def main(args: Array[String]): Unit = {
5 val list = List(1,2,3,4,5,6,7,8,9)
6
7 // 1. 过滤
8 // 选取偶数
9 val evenList = list.filter( (elem: Int) => {elem % 2 == 0} )
10 println(evenList)
11
12 // 选取奇数
13 println(list.filter( _ % 2 == 1 ))
14
15 println("=======================")
16
17 // 2. 映射map
18 // 把集合中每个数乘2
19 println(list.map(_ * 2))
20 println(list.map( x => x * x))
21
22 println("=======================")
23
24 // 3. 扁平化
25 val nestedList: List[List[Int]] = List(List(1,2,3),List(4,5),List(6,7,8,9))
26
27 val flatList = nestedList(0) ::: nestedList(1) ::: nestedList(2)
28 println(flatList)
29
30 val flatList2 = nestedList.flatten
31 println(flatList2)
32
33 println("=======================")
34
35 // 4. 扁平映射
36 // 将一组字符串进行分词,并保存成单词的列表
37 val strings: List[String] = List("hello world", "hello scala", "hello java", "we study")
38 val splitList: List[Array[String]] = strings.map( _.split(" ") ) // 分词
39 val flattenList = splitList.flatten // 打散扁平化
40
41 println(flattenList)
42
43 val flatmapList = strings.flatMap(_.split(" "))
44 println(flatmapList)
45
46 println("========================")
47
48 // 5. 分组groupBy
49 // 分成奇偶两组
50 val groupMap: Map[Int, List[Int]] = list.groupBy( _ % 2)
51 val groupMap2: Map[String, List[Int]] = list.groupBy( data => if (data % 2 == 0) "偶数" else "奇数")
52
53 println(groupMap)
54 println(groupMap2)
55
56 // 给定一组词汇,按照单词的首字母进行分组
57 val wordList = List("china", "america", "alice", "canada", "cary", "bob", "japan")
58 println( wordList.groupBy( _.charAt(0) ) )
59 }
60