【问题标题】:How to check map values from each map in the RDD using scala?如何使用scala检查RDD中每个地图的地图值?
【发布时间】:2015-01-19 09:41:28
【问题描述】:

我想检查 RDD 中每个地图的地图值,我的问题是

Let examples:RDD[Map[Int,String]]

即。

examples = 
Map(0 -> sunny, 1 -> hot, 2 -> high, 3 -> FALSE, 4 -> no)
Map(0 -> sunny, 1 -> hot, 2 -> high, 3 -> TRUE, 4 -> no)
Map(0 -> overcast, 1 -> hot, 2 -> high, 3 -> FALSE, 4 -> yes)
Map(0 -> rainy, 1 -> mild, 2 -> high, 3 -> FALSE, 4 -> yes)
Map(0 -> rainy, 1 -> cool, 2 -> normal, 3 -> FALSE, 4 -> yes)

我想检查每个 Map.ie 的最后一个键值对中的“值”,这里每个 Map 中的最后一个键值对是 4 -> no,4 -> no, 4 -> yes,。 ....从我需要检查该键值对中的值,即。 no,no,yes,yes,..... 如果都是“no”,则返回 no,否则返回“yes”。

【问题讨论】:

  • 地图中没有“最后一个键值对”(除非您使用的是 SortedMap。您知道最大索引将始终为 4 吗?
  • @Paul,我们可以从列数中找到最后一个索引。
  • 很奇怪。那为什么不使用列表呢?如果您知道您有条目 0... size-of-map - 1,则不需要地图。

标签: scala collections


【解决方案1】:
val examples = List(
  Map(0 -> "sunny", 1 -> "hot", 2 -> "high", 3 -> "FALSE", 4 -> "no"),
  Map(0 -> "sunny", 1 -> "hot", 2 -> "high", 3 -> "TRUE", 4 -> "no"),
  Map(0 -> "overcast", 1 -> "hot", 2 -> "high", 3 -> "FALSE", 4 -> "yes"),
  Map(0 -> "rainy", 1 -> "mild", 2 -> "high", 3 -> "FALSE", 4 -> "yes"),
  Map(0 -> "rainy", 1 -> "cool", 2 -> "normal", 3 -> "FALSE", 4 -> "yes"))

if (examples.forall(m => m(m.size - 1) == "yes")) 
  "yes"
else
  "no"

但这太可怕了。您的收藏选择令人怀疑。如果你有一个Map,你知道有来自0 .. <some-upper-bound>的键没有间隙,那么你有一个索引序列而不是Map,如果你使用一些IndexedSequence,你会发现操作它更容易(例如ListVector)。

适用于 RDD 的版本。关于收藏选择的评论仍然适用

val conf = new SparkConf().setAppName("spark-scratch").setMaster("local")
val sc= new SparkContext(conf)

val rdd  = sc.parallelize(examples, 1)

val yesno = rdd.map(m=>m(m.size - 1))
               .reduce ((l,r)=> if (l == "yes" && r == "yes") "yes" else "no")

【讨论】:

  • 我的 val 示例是 RDD[Map[Int,String]] 而不是 List[Map...]]。所以在这里我不能使用“forall”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-28
  • 1970-01-01
  • 2022-01-12
  • 2013-06-07
  • 1970-01-01
  • 2020-09-24
相关资源
最近更新 更多