Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
552 views
in Technique[技术] by (71.8m points)

scala - Get index of current element in a foreach method of Traversable?

Suppose I have two arrays:

val ar1 = Array[String]("1", "2", "3")
val ar2 = Array[String]("1", "2", "3", "4")

Now for each element of ar1, I want to first concatenate that element with the corresponding element of ar2, and then print the result. One way to do would be something like:

List.range(0, ar1.size).foreach(i => println(ar1(i)+ar2(i)))

It would have been nicer if there was a foreach variant that would allow me to work directly with the indices of ar1 instead of first constructing the integer list.

Perhaps there is a better way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One very convenient way to do this is with the zipped method on tuples. Put two collections in, get out two arguments to a function!

(ar1,ar2).zipped.foreach((x,y) => println(x+y))

This is both convenient to write and fast, since you don't need to build a tuple to store each pair (as you would with (ar1 zip ar2)) which you then have to take apart again. Both forms of zip stop when the shorter of the two collections is exhausted.

If you have something more complicated (e.g. you need to do math on the index), the canonical solution is to zip in the index:

ar1.zipWithIndex.foreach{ case(x,i) => println(x+ar2(i)) }

The method you are using is more rapidly and compactly done as follows, an can be useful:

ar1.indices.foreach(i => println(ar1(i)+ar2(i)))

although this only works if the first collection is no longer than the second. You can also specify your ranges explcitly:

(0 until (ar1.size min ar2.size)).foreach(i => println(ar1(i)+ar2(i)))

to get around this problem. (You can see why zip and zipped are preferred unless what you're doing is too complicated for this to work easily.)

If it is not a parallel collection (and usually it is not unless you call .par), it's also possible, though not recommended, to keep track with a mutable variable:

{ var i=-1; ar1.foreach{ x => i += 1; println(x+ar2(i)) } }

There are a very limited number of cases where this is necessary (e.g. if you may want to skip or backtrack on some of the other collection(s)); if you can avoid having to do this, you'll usually end up with code that's easier to reason about.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...