Search code examples
scala

Iterating over list of lists in scala


I was trying to loop over list of lists in scala. They may can have a single or multiple elements.

val condkeys=List(List("SITE"), List("SITEID"), List("NAME", "SITEID"))

var allcondkeys:Seq[String] =Seq.empty

for(index<-0 to 2)
{
val alias = ('b' + index).toChar
var key = s"$alias.${condkeys.lift(index).map(u=>u.mkString(",")).getOrElse("")}"
println(key)
allcondkeys=allcondkeys:+key
}

println(allcondkeys)
List(b.SITE, c.SITEID, d.NAME,SITEID)
println(allcondkeys.size)
3

I was expecting some output like as below. While iterating I want to alias them with a character. Char value should increase per iteration.

List(b.SITE, c.SITEID, d.NAME,d.SITEID)

Solution

  • This is a functional way of achieving what you want:

    val allcondkeys =
      for
        (list, index) <- condkeys.zipWithIndex
        elem <- list
      yield
        val key = ('b' + index).toChar
        s"$key.$elem"
    
    println(allcondkeys) // List(b.SITE, c.SITEID, d.NAME, d.SITEID)
    

    The equivalent using flatMap/map directly is this:

    val allcondkeys =
      condkeys.zipWithIndex.flatMap { (list, index) =>
        list.map { elem =>
          val key = ('b' + index).toChar
          s"$key.$elem"
        }
      }
    

    zipWithIndex adds the index to each element of the outer list. Then the appropriate character code is added to each element of the inner list for each element of the outer list. The final list is flattened into a single list of strings.

    The two version are functionally equivalent but the first is, perhaps, a bit clearer.