ftravers
ftravers

Reputation: 3999

how add incremented counter to each element of a list

I have:

scala> val alphaList = List("a", "b")
alphaList: List[java.lang.String] = List(a, b)

and I'd like a list of tuples like:

List((a,1),(b,2))

Normally in Java I'd do something like:

List alphaList = new ArrayList<String>()
alphaList.add("a");alphaList.add("b");
List newList = new ArrayList<String>();
for ( int i = 0; ii < alphaList.size(); i++ )
  newList.add(alphaList[i] + i);

What I'm trying to get at, is how do I get an incrementing variable that I can use while processing a List?

Upvotes: 1

Views: 3795

Answers (3)

Didier Dupont
Didier Dupont

Reputation: 29528

As an alternative to Axel22's answer, which is fine :

alphaList.zip(Stream.from(1))

Upvotes: 7

Landei
Landei

Reputation: 54584

How about...

def zipWithIndex1[A](xs:Seq[A]) = xs.map{var i = 0; x => i+=1; (x,i)}

Test:

zipWithIndex1("sdlfkjsdlf")
//--> Vector((s,1), (d,2), (l,3), (f,4), (k,5), (j,6), (s,7), (d,8), (l,9), (f,10))

Upvotes: 1

axel22
axel22

Reputation: 32335

alphaList.zipWithIndex.map {
  case (k, v) => (k, v + 1)
}

The zipWithIndex replaces each element with a tuple of itself and its index (starting from 0). The map matches the tuple, and creates a new tuple with the index incremented by 1, so that you start from 1, instead of 0.

Upvotes: 7

Related Questions