2

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.

1
  • 2
    Why do you need two variables here? Variables i and j always have the same value, haven't they? So why don't use i instead of j? If your real code is more complicated - show us some better example. Commented Nov 27, 2017 at 4:25

3 Answers 3

5

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

header.zip(cols).toMap
Sign up to request clarification or add additional context in comments.

2 Comments

When i added this line of code in programmer it doesn't iterates more than a single record.
@user1734980, I think you can paste a runnable code for this. if your header or cols not Scala Collection, maybe you need to convert it to Scala collection.
1

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))

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.