【问题标题】:How to use map / flatMap on a scala Map?如何在 Scala Map 上使用 map / flatMap?
【发布时间】:2018-05-07 13:34:51
【问题描述】:

我有两个序列,即prices: Seq[Price]overrides: Seq[Override]。我需要对它们做一些魔术,但只针对基于共享 id 的子集。

所以我通过groupBy将它们都分组为Map

我通过以下方式进行分组:

val pricesById = prices.groupBy(_.someId) // Int => Seq[Cruise]
val overridesById = overrides.groupBy(_.someId) // // Int => Seq[Override]

我希望能够通过flatMap 创建我想要的序列:

val applyOverrides = (someId: Int, prices: Seq[Price]): Seq[Price]  => {
  val applicableOverrides =  overridesById.getOrElse(someId, Seq())
  magicMethod(prices, applicableOverrides) // returns Seq[Price]
}

val myPrices: Seq[Price] = pricesById.flatMap(applyOverrides)

我预计myPrices 只包含一个大的Seq[Price]

但我在 flatMap 方法中遇到了一个奇怪的类型不匹配,我无法解决 NonInferedB。

【问题讨论】:

    标签: scala dictionary tuples sequence flatmap


    【解决方案1】:

    在 Scala 中,映射是元组,而不是键值对。

    flatMap 的函数因此只需要 一个 参数,即元组(key, value),而不是两个参数key, value

    由于您可以通过_1 访问元组的第一个元素,通过_2 访问第二个元素等等,您可以像这样生成您想要的函数:

    val pricesWithMagicApplied = pricesById.flatMap(tuple => 
      applyOverrides(tuple._1, tuple._2)
    

    另一种方法是用例匹配:

    val pricesWithMagicApplied: Seq[CruisePrice] = pricesById.flatMap {
      case (someId, prices) => applyOverrides(someId, prices)
    }.toSeq
    

    【讨论】:

    猜你喜欢
    • 2010-11-06
    • 1970-01-01
    • 2018-07-02
    • 2020-10-14
    • 1970-01-01
    • 2017-10-19
    • 1970-01-01
    • 2018-10-26
    • 1970-01-01
    相关资源
    最近更新 更多