I'm trying to update the value of an element of my Priority Queue of HashMaps put with no success. Here's is how I'm doing:
def HashMapOrdering = new Ordering[HashMap[Int,Int]] {
def compare(a : HashMap[Int,Int], b : HashMap[Int,Int]) = b.valuesIterator.next().compare(a.valuesIterator.next())
}
def main(args: Array[String]) {
var seeds = PriorityQueue[HashMap[Int, Int]]()(HashMapOrdering)
seeds.enqueue(HashMap(4 -> 4), HashMap(234 -> 5), HashMap(78 -> 6), HashMap(89 -> 1))
seeds.find(x => x.get(89) == 1) match {
case Some(hashMap: HashMap[Int, Int]) => hashMap.remove(77); hashMap.put(77,32)
case None => println("Not found")
}
}
Unfortunately, I always got the "Not found" message. Any ideias on what am I doing wrong or how to update the hash's values?
Obviously you've got a type mismatch. If you look the definition of get
function, you'll see the following ( http://www.scala-lang.org/api/2.11.6/index.html#scala.collection.mutable.HashMap ):
def get(key: A): Option[B]
That means, that it returns value in your case typed as Option[Int]
. So wrap your right condition argument in an Option
monad:
seeds.find(x => x.get(89) == Some(1)) match {
case Some(hashMap: HashMap[Int, Int]) => {
hashMap.remove(77)
hashMap.put(77,32)
}
case None => println("Not found")
}
Works as expected.
PS Forgot about your question about updating: you can use an update
function instead of using remove
and put
: hashMap.update(77, 32)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.