user461112
user461112

Reputation: 4151

Finding a map in list/vector of maps in Scala

I have a vector/list of maps (Map[String,Int]). How can I find if a key-value pair exists in one of these maps in the list of maps using .find?

Upvotes: 0

Views: 649

Answers (3)

RAGHHURAAMM
RAGHHURAAMM

Reputation: 1099

It can be done even like this using just the key value we are interested to find:

scala> val res = List(Map("A" -> 10), Map("B" -> 20)).find(_.keySet.contains("B"))
res: Option[scala.collection.immutable.Map[String,Int]] = Some(Map(B -> 20))

scala>

Upvotes: 0

ziggystar
ziggystar

Reputation: 28680

chengpohi's solution is pretty inefficient, and also different to how I understand the question.

Let m: Map[String,Int].

Why chengpoi's solution is inefficient

First, using m.exists(j => j == ("2",2)), which can also be written m.contains("2" -> 2) looks at every entry of m, while m("2").toSeq.contains(2) performs only a single map lookup. Note that m.contains("2" -> 2) will not work, as contains is overridden for Map to check for a key, i.e., m.contains("2") works—and is also fast.

To obtain the same result as chengpoi, but efficiently:

def mapExists[K,V](ms: List[Map[K,V]], k: K, v: V): Option[(K,V)] = 
    ms.get(k).filter(_ == v).map(_ => k -> v)

Note that this method returns its arguments, which is quite redundant.

How I understand the question

Second, I understood the question as checking whether the List contains a Map with a specific pair. This would translate to

def mapExists[K,V](ms: List[Map[K,V]], k: K, v: V): Boolean = 
    ms.exists(_.get(k).contains(v))

Upvotes: 1

chengpohi
chengpohi

Reputation: 14217

val res = List(Map("1" -> 1), Map("2" -> 2)).find(t => t.exists(j => j == ("2", 2)))
println(res)

use find with exists to check whether it exists in maps.

Upvotes: 2

Related Questions