我有一个包含许多字段的 Person 对象列表,我可以轻松做到:
list.map(person => person.getName)
为了生成另一个包含所有人员姓名的集合。
如何使用映射函数创建一个包含 Person 类的所有字段(但不包含其名称)的新集合?
换句话说,如何从给定集合中创建一个新集合,该集合将包含初始集合的所有元素,并删除其中的一些字段?
最佳答案
您可以使用 case 类
的 unapply
方法将成员提取为 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))
关于Scala 映射函数删除字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39775180/