david419 david419 - 1 year ago 183
Scala Question

How to iterate over MultiValueMap of type <String,Any> where <Any> can be another MultiValueMap and so on

I want to iterate over a

of type
where Any can be another
of type
and the Any can be another MultiValeMap and so on. The code I have is to extract only the first level of the Map:- ("result" variable is the

val entrySet = result.entrySet();
val it = entrySet.iterator();
//System.out.println(" Object key Object value");
while (it.hasNext()) {
val mapEntry= it.next().asInstanceOf[java.util.Map.Entry[String,Any]];
val list = (result.get(mapEntry.getKey()).asInstanceOf[List[String]])
for (j <- 0 to list.size - 1) {
System.out.println("\t" + mapEntry.getKey() + "\t " + list.get(j));

Answer Source

One approach is to collect all the elements (key->value pairs) and then turn the accumulated collection into an iterator.

def toItr(m: Map[String,_]): Iterator[(String,_)] =
    case (acc, (k, v: Map[String,_])) => acc ++ toItr(v).toVector
    case (acc, x) => acc :+ x

toItr( Map("a"->1, "b"->3, "c"->Map("x"->11, "y"->22)) )
// result: Iterator[Tuple2[String, _]] = non-empty iterator
// contents: (a,1), (b,3), (x,11), (y,22)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download