过滤

  1. 遍历一个集合并从中获取满足指定条件的元素组成一个新的集合
  1. val list = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
  2. //过滤
  3. //选取偶数
  4. val evenList = list.filter((elem: Int) => {
  5. elem % 2 == 0
  6. })
  7. println(evenList) //List(2, 4, 6, 8)
  8. //选取奇数
  9. println(list.filter(_ % 2 == 1)) //List(1, 3, 5, 7, 9)

转化/映射(map)

  1. 将集合中的每一个元素映射到某一个函数
  1. val list = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
  2. //map
  3. //把集合中每个数乘2,平方
  4. println(list.map(_ * 2)) //List(2, 4, 6, 8, 10, 12, 14, 16, 18)
  5. println(list.map(x => x * x)) //List(1, 4, 9, 16, 25, 36, 49, 64, 81)

扁平化

  1. //扁平化
  2. val nestedList:List[List[Int]] = List(List(1,2,3),List(4,5,6),List(7,8,9))
  3. val flatList = nestedList(0) ::: nestedList(1) ::: nestedList(2)
  4. println(flatList) //List(1, 2, 3, 4, 5, 6, 7, 8, 9)
  5. val flatList2 = nestedList.flatten
  6. println(flatList2) //List(1, 2, 3, 4, 5, 6, 7, 8, 9)

扁平化+映射

注:flatMap相当于先进行map操作,在进行flatten操作
集合中的每个元素的子元素映射到某个函数并返回新集合

  1. //扁平映射
  2. //将一组字符串进行分词,并保存成单词的列表
  3. val strings: List[String] = List("hello world", "hello scala", "hello java", "we study")
  4. val splitList: List[Array[String]] = strings.map(_.split(" ")) //分词
  5. val flattenList = splitList.flatten
  6. println(flattenList) //List(hello, world, hello, scala, hello, java, we, study)
  7. println(strings.flatMap(_.split(" "))) //List(hello, world, hello, scala, hello, java, we, study)

分组(group)

  1. 按照指定的规则对集合的元素进行分组
  1. //分组groupBy
  2. //分成奇偶两组
  3. val groupMap = list.groupBy(_ % 2)
  4. val groupMap2 = list.groupBy(data => if (data % 2 == 0) "偶数" else "奇数")
  5. println(groupMap) //Map(1 -> List(1, 3, 5, 7, 9), 0 -> List(2, 4, 6, 8))
  6. println(groupMap2) //Map(奇数 -> List(1, 3, 5, 7, 9), 偶数 -> List(2, 4, 6, 8))
  7. //给定一组词汇,按照单词的首字母进行分组
  8. val wordList = List("china", "america", "alice", "canada", "cary", "bob", "japan")
  9. println(wordList.groupBy(_.charAt(0))) //Map(b -> List(bob), j -> List(japan), a -> List(america, alice), c -> List(china, canada, cary))

简化(归约)

  1. //Reduce
  2. println(list.reduce(_ + _)) //10
  3. println(list.reduceLeft(_ + _)) //10
  4. println(list.reduceRight(_ + _)) //10
  5. val list2 = List(3, 4, 5, 8, 10)
  6. println(list2.reduce(_ - _)) //-24
  7. println(list2.reduceLeft(_ - _)) //-24
  8. println(list2.reduceRight(_ - _)) //6
  9. //fold
  10. println(list.fold(10)(_ + _)) //20
  11. println(list.foldLeft(10)(_ - _)) //0
  12. println(list2.foldRight(11)(_ - _)) //3 - (4 - (5 - (8 - (10 - 11)))),-5