Reputation: 4861
Suppose I have an array of strings in Scala:
val strings = Array[String]("1", "2", "3", "4", "5", "6", "7")
What I need is to make a new array which elements will be obtained as a concatenation of each three (any number) consequent elements of the first array, which should result in ("123", "456", "7")
Being new to Scala I wrote the following code which was neither concise nor effective:
var step = 3
val strings = Array[String]("1", "2", "3", "4", "5", "6", "7")
val newStrings = collection.mutable.ArrayBuffer.empty[String]
for (i <- 0 until strings.length by step) {
var elem = ""
for (k <- 0 until step if i + k < strings.length) {
elem += strings(i + k)
}
newStrings += elem
}
What would be the Scala way for doing this?
Upvotes: 2
Views: 529
Reputation: 36259
... or use sliding
val strings = Array[String]("1", "2", "3", "4", "5", "6", "7")
strings.sliding (3, 3) .map (_.mkString).toArray
res19: Array[String] = Array(123, 456, 7)
Sliding: You take 3, and move forward 3. Variants:
scala> strings.sliding (3, 2) .map (_.mkString).toArray
res20: Array[String] = Array(123, 345, 567)
take 3, but forward 2
scala> strings.sliding (2, 3) .map (_.mkString).toArray
res21: Array[String] = Array(12, 45, 7)
take 2, forward 3 (thereby skipping every third)
Upvotes: 3
Reputation: 67888
strings grouped 3 map (_.mkString)
or (in order to really get an Array
back)
(strings grouped 3 map (_.mkString)).toArray
Upvotes: 4
Reputation: 27250
strings.grouped(3).map(_.mkString).toArray
or
strings grouped 3 map (_.mkString) toArray
I personally prefer the first version :)
Upvotes: 9