如何根据scala中的内部地图值访问地图的地图

how to access map of map based on inside map value in scala

我有地图src_grp_map的地图。现在我想获取内部地图,它在内部地图中加入 table 键时具有模式字符串 edw.cdim_country。

下面是我的地图源图

      val src_grp_map=Map("edw.dim_cust_extn_odm" -> 
        Map("src_table" -> "edw.dim_cust_extn_odm", "tgt_attribute_count" -> 3, "join_table" -> "edw.dim_cust,edw.cdim_country,NA"),
        "edw.dw_atk_case_general" -> 
          Map("src_table" -> "edw.dw_atk_case_general", "tgt_attribute_count" -> 2, "join_table" -> "NA"))

现在使用 src_grp_map 我想要在 join_table 键中包含 edw.cdim_country 的内部地图 输出应该在下面。

Map("src_table" -> "edw.dim_cust_extn_odm", "tgt_attribute_count" -> 3, "join_table" -> "edw.dim_cust,edw.cdim_country,NA")

如果多个内部映射包含模式字符串,那么我需要所有内部映射。

这听起来是个有趣的问题。但是,我认为有一件事会对你有很大帮助。当前,src_grp_map 的类型为 Map[String, Map[String, AnyVal]]。我认为将其设为 Map[String, CustomClass] 类型会更好。

所以这是我的首选解决方案:

case class TableInfo(srcTable: String, tgtAttributeCount: Int, joinTable: IndexedSeq[String])

val info1 = TableInfo("edw.dim_cust_extn_odm", 3, IndexedSeq("edw.dim_cust", "edw.cdim_country", "NA"))
val info2 = TableInfo("edw.dw_atk_case_general", 2, "NA")

val srcGrpMap = Map("edw.dim_cust_extn_odm" -> info1, "edw.dw_atk_case_general" -> info2)

def getTableInfo(joinTableKey: String, inputMap: Map[String, TableInfo]): IndexedSeq[TableInfo] = inputMap.values.filter(_.joinTable.contains(joinTableKey))

只需调用 getTableInfo 函数即可。

现在,如果您坚持使用原来笨重的数据格式,这里有一个替代解决方案:

def getTableInfo(joinTableKey: String, inputMap: Map[String, Map[String, AnyVal]]): IndexedSeq[Map[String, AnyVal]] = {
  inputMap.values.filter{ x =>
    x.get("join_table") match {
      case Some(y) =>
        y match {
          case z: String =>
            z.split(",").contains(joinTableKey)
          case z => false
        }
      case None => 
        false
    }
  }.toIndexedSeq
}

我使用下面的代码成功实现了它。

     val src_grp_map=Map("edw.dim_cust_extn_odm" ->
      Map("src_table" -> "edw.dim_cust_extn_odm", "tgt_attribute_count" -> 3, "join_table" -> "edw.dim_cust,edw.cdim_country,NA"),
      "edw.dw_atk_case_general" ->
        Map("src_table" -> "edw.dw_atk_case_general", "tgt_attribute_count" -> 2, "join_table" -> "NA"))

    val collect_src_table_values=src_grp_map.map(p=>p._2).toList

    val z=collect_src_table_values.filter(x=>x("join_table").toString().contains("edw.cdim_country"))