过滤
遍历一个集合并从中获取满足指定条件的元素组成一个新的集合
val list = List(1, 2, 3, 4, 5, 6, 7, 8, 9)//过滤//选取偶数val evenList = list.filter((elem: Int) => {elem % 2 == 0})println(evenList) //List(2, 4, 6, 8)//选取奇数println(list.filter(_ % 2 == 1)) //List(1, 3, 5, 7, 9)
转化/映射(map)
将集合中的每一个元素映射到某一个函数
val list = List(1, 2, 3, 4, 5, 6, 7, 8, 9)//map//把集合中每个数乘2,平方println(list.map(_ * 2)) //List(2, 4, 6, 8, 10, 12, 14, 16, 18)println(list.map(x => x * x)) //List(1, 4, 9, 16, 25, 36, 49, 64, 81)
扁平化
//扁平化val nestedList:List[List[Int]] = List(List(1,2,3),List(4,5,6),List(7,8,9))val flatList = nestedList(0) ::: nestedList(1) ::: nestedList(2)println(flatList) //List(1, 2, 3, 4, 5, 6, 7, 8, 9)val flatList2 = nestedList.flattenprintln(flatList2) //List(1, 2, 3, 4, 5, 6, 7, 8, 9)
扁平化+映射
注:flatMap相当于先进行map操作,在进行flatten操作
集合中的每个元素的子元素映射到某个函数并返回新集合
//扁平映射//将一组字符串进行分词,并保存成单词的列表val strings: List[String] = List("hello world", "hello scala", "hello java", "we study")val splitList: List[Array[String]] = strings.map(_.split(" ")) //分词val flattenList = splitList.flattenprintln(flattenList) //List(hello, world, hello, scala, hello, java, we, study)println(strings.flatMap(_.split(" "))) //List(hello, world, hello, scala, hello, java, we, study)
分组(group)
按照指定的规则对集合的元素进行分组
//分组groupBy//分成奇偶两组val groupMap = list.groupBy(_ % 2)val groupMap2 = list.groupBy(data => if (data % 2 == 0) "偶数" else "奇数")println(groupMap) //Map(1 -> List(1, 3, 5, 7, 9), 0 -> List(2, 4, 6, 8))println(groupMap2) //Map(奇数 -> List(1, 3, 5, 7, 9), 偶数 -> List(2, 4, 6, 8))//给定一组词汇,按照单词的首字母进行分组val wordList = List("china", "america", "alice", "canada", "cary", "bob", "japan")println(wordList.groupBy(_.charAt(0))) //Map(b -> List(bob), j -> List(japan), a -> List(america, alice), c -> List(china, canada, cary))
简化(归约)
//Reduceprintln(list.reduce(_ + _)) //10println(list.reduceLeft(_ + _)) //10println(list.reduceRight(_ + _)) //10val list2 = List(3, 4, 5, 8, 10)println(list2.reduce(_ - _)) //-24println(list2.reduceLeft(_ - _)) //-24println(list2.reduceRight(_ - _)) //6//foldprintln(list.fold(10)(_ + _)) //20println(list.foldLeft(10)(_ - _)) //0println(list2.foldRight(11)(_ - _)) //3 - (4 - (5 - (8 - (10 - 11)))),-5
