Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to join two array is scala

suppose I have two arrays

val x =Array("one","two","three")
val y =Array("1","2","3")

what's the most elegant way to get a new array like ["one1","two2","three3"]

like image 724
Jade Tang Avatar asked Dec 04 '22 04:12

Jade Tang


2 Answers

Using zip and map should do it:

(x zip y) map { case (a, b) => a + b }
like image 154
Michael Zajac Avatar answered Dec 18 '22 17:12

Michael Zajac


Similarly to @m-z, with a for comprehension, like this,

for ( (a,b) <- x zip y ) yield a + b

This can be encapsulated into an implicit such as

implicit class StrArrayOps(val x: Array[String]) extends AnyVal { 
  def join(y: Array[String]) = 
    for ( (a,b) <- x zip y ) yield a + b 
}

and use it like this,

x join y
Array(one1, two2, three3)
like image 40
elm Avatar answered Dec 18 '22 16:12

elm