I have an array like this
(20140101,20140102,20140103,20140104,20140105,20140106,20140107,20140108)
I want to create a map from this by prefixing each value with "s3://" and concatenating three values with a comma.
Output:
val params = Map("1"-> "s3://20140101,s3://20140102,s3://20140103","2"-> "s3://20140104,s3://20140105,s3://20140106","3"->"s3://20140107,s3://20140108")
I'm a beginner and kindly request some thoughts here.
This returns a Map[Int, Array[String]]
. If you really want the values as a String
, then use mapValues(_.mkString(","))
on the result.
scala> val xs = Array(20140101,20140102,20140103,20140104,20140105,20140106,20140107,20140108)
xs: Array[Int] = Array(20140101, 20140102, 20140103, 20140104, 20140105, 20140106, 20140107, 20140108)
scala> xs.map(x => "s3://" + x).grouped(3).zipWithIndex.map(t => (t._2, t._1)).toMap
res16: scala.collection.immutable.Map[Int,Array[String]] = Map(0 -> Array(s3://20140101, s3://20140102, s3://20140103), 1 -> Array(s3://20140104, s3://20140105, s3://20140106), 2 -> Array(s3://20140107, s3://20140108))
I think this will do what you want:
val array = Array(20140101, 20140102, 20140103, 20140104, 20140105, 20140106, 20140107, 20140108)
val result = array.
sliding(3, 3). // this selects 3 elements at a time and steps 3 elements at a time
zipWithIndex. // this adds an index to the 3 elements
map({ case (arr, i) => (i + 1).toString -> arr.map(a => "s3://" + a.toString).mkString(",")}). // this makes a tuple and concats the array elements
toMap // this transforms the Array of tuples into a map
println(result)
//prints Map(1 -> s3://20140101,s3://20140102,s3://20140103, 2 -> s3://20140104,s3://20140105,s3://20140106, 3 -> s3://20140107,s3://20140108)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With