Scala 映射函数删除字段

标签 scala function lambda functional-programming

我有一个包含许多字段的 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/

相关文章:

scala - 测试已弃用的 Scala 函数时如何抑制弃用警告?

c++ - 函数调用不显示 cout

function - Scheme中函数的机制

python - Python 中的 max() 表达式如何工作?

java - 为什么 Java 8 没有 "myArray.stream()"函数?

java - 为什么invokeLater在主线程中执行?

java - scalac v javac 和 scala v java

scala - 关于 Play with scala 模块方法的说明

scala - 玩框架如何重用和扩展表单映射

将字符串中每个单词的首字母大写并进行字数统计