user1734980
user1734980

Reputation: 45

Multiple variable loop in scala

I wants to iterate two variable in loop and populate the map.Java code looks like below.

for (int i = 0, j = 0; i < header.size(); i++, j++)
{
  map.put(header.get(i), cols.get(j));
}

How can we achieve this in Scala? Please can anyone help on this? Help appreciated.

Upvotes: 2

Views: 345

Answers (3)

Aluan Haddad
Aluan Haddad

Reputation: 31823

I was going to suggest

val map = (0 until header.size) map { n => header.get(n) -> header.col(n) } toMap

As a fairly naive translation.

This assumes that header is just an arbitrary object with a few defs, not a proper collection.

Upvotes: 1

prayagupadhyay
prayagupadhyay

Reputation: 31222

One way is map over your headers along with the index of each entry and get the col for the same index and create a map.

Given,

scala> val headers = Seq("h1", "h2", "h3", "h4")
headers: Seq[String] = List(h1, h2, h3, h4)

scala> val cols = Seq("c1", "c2", "c3")
cols: Seq[String] = List(c1, c2, c3)

map on headers cols.lift(i) is safe way when headers.size > cols.size

scala> headers.zipWithIndex.map{case (h, i) => h -> cols.lift(i).getOrElse("")}.toMap
res50: scala.collection.immutable.Map[String,String] = Map(h1 -> c1, h2 -> c2, h3 -> c3, h4 -> "")

If headers.size == cols.size or if you don't want header which does not have equvalent col, you can use list.zip(anotherList),

scala> headers.zip(cols)
res52: Seq[(String, String)] = List((h1,c1), (h2,c2), (h3,c3))

Upvotes: 1

chengpohi
chengpohi

Reputation: 14217

In Scala, you can use zip to do this, like:

header.zip(cols).toMap

Upvotes: 5

Related Questions