首页 > 解决方案 > 如何在scala中过滤掉2个不同地图的公共键

问题描述

我想检索一个列表/数组(假设A)的键值,该键存在于另一个列表/数组中(假设B)

val B: List[String] = List("key1","key3")  //I can refactor the type if needed

val paramNames: Array[String] = parameterNames  // ["key1", "key2", "key3"]
val paramValues: Array[AnyRef] = args //  [1, "value", Obj]

val A: Array[(String,AnyRef)] = paramNames.zip(paramValues) //  [("key1", 1), ("key2", "value"), ("key3", Obj)]

//now I want to retrieve from A, all keys exist in B with their values
//to get [("key1", 1), ("key3", Obj)]

标签: arraysscalafiltercollectionstuples

解决方案


只需使用过滤器:

val C = A.filter(k => B.contains(k._1))

这将只获得元组,其键包含在B.


推荐阅读