david419 david419 - 2 months ago 41
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

MultiValueMap
of type
<String,Any>
where Any can be another
MultiValueMap
of type
<String,Any>
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
MultiValueMap
)

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) {
//mapEntry.setValue("dhjgdj")
System.out.println("\t" + mapEntry.getKey() + "\t " + list.get(j));
}
}

Answer

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,_)] =
  m.foldLeft(Vector.empty[(String,_)]){
    case (acc, (k, v: Map[String,_])) => acc ++ toItr(v).toVector
    case (acc, x) => acc :+ x
  }.toIterator

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)