對映和過濾集合

地圖

跨集合的對映使用 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 )