【问题标题】:Scala map function to remove fieldsScala 映射函数来删除字段
【发布时间】:2016-09-29 16:08:57
【问题描述】:

我有一个包含许多字段的 Person 对象列表,我可以轻松做到:

list.map(person => person.getName)

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

您如何使用 map 函数创建一个包含 Person 类的所有字段的新集合,但它们的名称?

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

【问题讨论】:

  • 你的问题没有很好的定义。我猜你有一堆“getter”函数,你想要像list.map(person => Seq(person.getHeight, person.getWeight)) 这样的东西。为了做到这一点,Scala 必须知道哪些函数是“getter”函数。您当然可以通过在 Person 类中维护“getter”函数列表并从该列表中过滤掉 getName 来做到这一点,但是维护起来很乏味。另外值得注意的是,Scala 风格通常避免使用 getter 和 setter 来支持不可变变量。你能描述一下你为什么要这样做吗?
  • 在我的例子中,Person 对象实际上是一个具有许多 getter 的不可变 Java 对象——我曾想过使用一些反射来检索它的所有方法,然后将它们过滤掉,但这确实太乏味了。我还可以使用 map 函数来指定我想映射到哪些 getter 方法,但是如果要映射的 getter 比要排除的多,那也可能会变得乏味。我希望 scala 可以提供一些可以在这种情况下使用的单行魔法。
  • 您可以扩展Person 类以创建Map 字段,然后您可以轻松过滤。 implicit class extendPerson(p: Person) { def getAllFields: Map[String, String] = Map("name" -> p.getName, "age" ->p.getAge, ...) 然后person.getAllFields.filterKeys(k => k != "name")

标签: scala function lambda functional-programming


【解决方案1】:

您可以使用case classunapply 方法将成员提取为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))

【讨论】:

  • 单个解析可以简化:map{case Person(_, age, country) => (age, country)}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-27
  • 2023-03-19
  • 2018-01-22
  • 2018-04-25
  • 1970-01-01
相关资源
最近更新 更多