![](/img/trans.png)
[英]How to retrive keys by comparing values of map list from config in scala
[英]Scala comparing two Map's keys and values
上下文是在Scala中比較兩個Map的鍵和值,但我不確定我是否知道如何正確地問這個。 假設我有兩個案例類
case class WhiteList(attributes: Option[Map[String, Set[String]]])
和
case class Query(attributes: Option[Map[String, Set[String]]])
我想比較這兩個類之間屬性的值,如果屬性映射中的鍵是相同的,否則返回false
。
所以,如果我有
val wl = WhiteList(attributes = Some(Map("patterns" -> Set("plaid"),
"colors" -> Set("blue", "orange")))
和
val q = Query(attributes = Some(Map("patterns" -> Set("plaid"),
"colors" -> Set("orange")))
如果我比較這兩個,我想返回true
因為:1)它們具有相同的Map鍵和2)相應鍵的值相交
如果我有
val q2 = Query(attributes = Some(Map("patterns" -> Set("stripes"),
"colors" -> Set("orange", "red", "blue")))
並且將相應鍵的值與wl進行比較,我想要false
因為“模式”值不相交。
如果我有
val q3 = Query(attributes = Some(Map("starwars" -> Set("a new hope", "empire strikes back"),
"patterns" -> Set("stripes"),
"colors" -> Set("orange", "red", "blue")))
並且將q3與wl進行比較,我認為是false
,因為屬性的鍵不是一對一的。
我認為必須有一種功能性的方法來做到這一點。
也許是這樣的?
def areEqual(wl: WhiteList, q: Query) = (wl, q) match {
case (WhiteList(Some(map1)), Query(Some(map2))) =>
map1.keySet == map2.keySet &&
map1.keySet.forall(key => (map1(key) intersect map2(key)).nonEmpty)
case _ => false
}
在repl中測試:
val wl = WhiteList(attributes = Some(Map("patterns" -> Set("plaid"),
"colors" -> Set("blue", "orange"))))
val q = Query(attributes = Some(Map("patterns" -> Set("plaid"),
"colors" -> Set("orange"))))
val q2 = Query(attributes = Some(Map("patterns" -> Set("stripes"),
"colors" -> Set("orange", "red", "blue"))))
val q3 = Query(attributes = Some(Map("starwars" -> Set("a new hope", "empire strikes back"),
"patterns" -> Set("stripes"),
"colors" -> Set("orange", "red", "blue"))))
scala> areEqual(wl, q)
res4: Boolean = true
scala> areEqual(wl, q2)
res5: Boolean = false
scala> areEqual(wl, q3)
res6: Boolean = false
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.