在scalaMap中查找值重叠的键集

vd2z7a6w  于 2021-05-27  发布在  Spark
关注(0)|答案(1)|浏览(408)

我在scala中使用一个map对象,其中键是一个篮子id,值是篮子中包含的一组项目id。目标是接收这个Map对象,并为每个篮子计算一组至少包含一个公共项的其他篮子id。
假设输入Map对象是 val basket = Map("b1" -> Set("i1", "i2", "i3"), "b2" -> Set("i2", "i4"), "b3" -> Set("i3", "i5"), "b4" -> Set("i6")) 有没有可能在spark中执行计算,这样我就可以得到相交的篮子信息?例如 val intersects = Map("b1" -> Set("b2", "b3"), "b2" -> Set("b1"), "b3" -> Set("b1"), "b4" -> Set()) 谢谢!

gzszwxb4

gzszwxb41#

有点像。。。

val basket = Map("b1" -> Set("i1", "i2", "i3"), "b2" -> Set("i2", "i4"), "b3" -> Set("i3", "i5"), "b4" -> Set("i6"))

def intersectKeys( set : Set[String], map : Map[String,Set[String]] ) : Set[String] = {
  val checks = map.map { case (k, v) =>
    if (set.intersect(v).nonEmpty) Some(k) else None
  }
  checks.collect { case Some(k) => k }.toSet
}

// each set picks up its own key, which we don't want, so we subtract it back out
val intersects = basket.map { case (k,v) => (k, intersectKeys(v, basket) - k) }

相关问题