Scala 映射函数删除字段

ant*_*n4o 2 lambda functional-programming scala function

我有一个包含许多字段的 Person 对象列表,我可以轻松地执行以下操作:

list.map(person => person.getName)
Run Code Online (Sandbox Code Playgroud)

为了生成另一个包含所有人民姓名的集合。

如何使用 map 函数创建一个包含 Person 类的所有字段(但不包含其名称)的新集合?

换句话说,如何从给定集合中创建一个新集合,该集合将包含初始集合的所有元素,并删除其中的一些字段?

Sar*_*ngh 5

您可以使用unapply您的方法case class来提取成员,tuple然后从tuple.

case class Person(name: String, Age: Int, country: String)
// defined class Person

val personList = List(
  Person("person_1", 20, "country_1"),
  Person("person_2", 30, "country_2")
)
// personList: List[Person] = List(Person(person_1,20,country_1), Person(person_2,30,country_2))

val tupleList = personList.flatMap(person => Person.unapply(person))
// tupleList: List[(String, Int, String)] = List((person_1,20,country_1), (person_2,30,country_2))

val wantedTupleList = tupleList.map({ case (name, age, country) => (age, country) })
// wantedTupleList: List[(Int, String)] = List((20,country_1), (30,country_2))

// the above is more easy to understand but will cause two parses of list
// better is to do it in one parse only, like following

val yourList = personList.flatMap(person => {
  Person.unapply(person) match {
    case (name, age, country) => (age, country)
  }
})
// yourList: List[(Int, String)] = List((20,country_1), (30,country_2))
Run Code Online (Sandbox Code Playgroud)

  • 单个解析可以简化:`map{case Person(_,age,country) => (age,country)}` (2认同)