映射和过滤集合

地图

跨集合的映射使用 map 函数以类似的方式转换该集合的每个元素。一般语法是:

val someFunction: (A) => (B) = ???
collection.map(someFunction)

你可以提供匿名功能:

collection.map((x: T) => /*Do something with x*/)

将整数乘以 2

// Initialize 
val list = List(1,2,3)
// list: List[Int] = List(1, 2, 3)

// Apply map
list.map((item: Int) => item*2)
// res0: List[Int] = List(2, 4, 6)

// Or in a more concise way
list.map(_*2)
// res1: List[Int] = List(2, 4, 6)

过滤

当你想要排除或过滤掉集合的某些元素时,使用 filter。与 map 一样,一般语法需要一个函数,但该函数必须返回一个 Boolean

val someFunction: (a) => Boolean = ???
collection.filter(someFunction)

你可以直接提供匿名功能:

collection.filter((x: T) => /*Do something that returns a Boolean*/)

检查对号

val list = 1 to 10 toList
// list: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

// Filter out all elements that aren't evenly divisible by 2
list.filter((item: Int) => item % 2==0)
// res0: List[Int] = List(2, 4, 6, 8, 10)

更多地图和过滤器示例

case class Person(firstName: String,
                  lastName: String,
                  title: String)

// Make a sequence of people
val people = Seq(
  Person("Millie", "Fletcher", "Mrs"),
  Person("Jim", "White", "Mr"),
  Person("Jenny", "Ball", "Miss") )

// Make labels using map
val labels = people.map( person =>
  s"${person.title}. ${person.lastName}"
)

// Filter the elements beginning with J
val beginningWithJ = people.filter(_.firstName.startsWith("J"))

// Extract first names and concatenate to a string
val firstNames = people.map(_.firstName).reduce( (a, b) => a + "," + b )