0

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));
    }
}
jrbedard
  • 3,662
  • 5
  • 30
  • 34
david419
  • 435
  • 3
  • 8
  • 18

1 Answers1

2

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)
jwvh
  • 50,871
  • 7
  • 38
  • 64
  • Thanks for the reply jwvh. I want to apply this during saxParsing an XML. So at every step I have to iterate to the root node of the current element I am parsing and add the child there to the MultiValueMap. So do I have to create an iterator every time the MultiValueMap gets updated? – david419 Sep 26 '16 at 03:56
  • If I understand your question correctly, it sounds like the answer is yes, a new `Iterator` would be needed for every sub-`Map`/`Iterator`. – jwvh Sep 26 '16 at 04:10