dedpo dedpo - 10 months ago 79
Scala Question

how to use option on a multimap in scala

I have map and mutlimap, because map can't have duplicate keys, decide to try and implement multip so i can have dup keys.

val linkDatabase = Map(
"100" -> "101",
"100" -> "102",
"101" -> "106",
"102" -> "107",
"103" -> "108",
"104" -> "109",
"105" -> "110",
"106" -> "111",
"107" -> "112",
"108" -> "113",
"109" -> "114",
"110" -> "115")

def ListofConnections1(key : String): List[String] = {
Iterator.iterate(Option(key))(o => linkDatabase.get(o.head))
.takeWhile(_.nonEmpty).flatten.toList
}


This returns list
100, 102, 107, 112
when you call ListofConnections("100")

Like wise the same as above in multi map is implemented, but the difference is we have 100 as key twice acceptable due to multimap

import collection.mutable.{ HashMap, MultiMap, Set }
val mm = new HashMap[String, Set[String]] with MultiMap[String, String]

mm.addBinding("100", "101")
mm.addBinding("100", "102")
mm.addBinding("101", "106")
mm.addBinding("102" , "107")
mm.addBinding("103" , "108")
mm.addBinding("104", "109")
mm.addBinding("105", "110")
mm.addBinding("106", "111")
mm.addBinding("107", "112")
mm.addBinding("108" , "113")
mm.addBinding("109", "114")
mm.addBinding("110" , "115")

def ListofConnections2(key : String): List[String] = {
Iterator.iterate(Option(key))(o => mm.toMap.get(o.head))
.takeWhile(_.nonEmpty).flatten.toList
}


I am trying to use this function like above but i get different errors like, i am not sure how to use the
option
alias
o
here to

found : Option[scala.collection.mutable.Set[String]]
required: Option[String]
Iterator.iterate(Option(key))(o => mm.get(o.head))


The expected result when i call ListofConnections2("100") is THIS list:
100, 101, 102, 107, 112

Answer Source

This will work for you;

def ListofConnections2(key : String): List[String] = mm.get(key) match {
  case None => Nil
  case Some(keys) =>
    keys.toList ++ keys.flatMap(ListofConnections2)
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download