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?
The
zipWithIndexreplaces each element with a tuple of itself and its index (starting from 0). Themapmatches the tuple, and creates a new tuple with the index incremented by 1, so that you start from 1, instead of 0.