Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - converting array to map

Tags:

scala

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.

like image 806
user3279189 Avatar asked Nov 19 '14 18:11

user3279189


2 Answers

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))
like image 107
Brian Avatar answered Oct 20 '22 19:10

Brian


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)
like image 42
Noah Avatar answered Oct 20 '22 21:10

Noah