Scala - 将数组转换为map

时间:2014-11-19 18:06:07

标签: scala

我有一个像这样的数组

(20140101,20140102,20140103,20140104,20140105,20140106,20140107,20140108)

我想通过在每个值前加上“s3://”并使用逗号连接三个值来创建一个映射。

输出:

val params = Map("1"-> "s3://20140101,s3://20140102,s3://20140103","2"-> "s3://20140104,s3://20140105,s3://20140106","3"->"s3://20140107,s3://20140108")

我是初学者,请在这里提出一些想法。

4 个答案:

答案 0 :(得分:9)

这会返回Map[Int, Array[String]]。如果您确实希望将值设为String,请在结果上使用mapValues(_.mkString(","))

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))

答案 1 :(得分:4)

我认为这会做你想做的事情:

  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)

答案 2 :(得分:0)

只是另一种变体,这次避免了zipWithIndex和键值交换

val xs = Array(20140101,20140102,20140103,20140104,20140105,20140106,20140107,20140108)

Iterator.from(0).zip{xs.grouped(3).map{"s://"+ _.mkString(",")}}.toMap

答案 3 :(得分:0)

您可以将其转换为元组,然后将该元组转换为映射。像这样:

val xs = Array(20140101,20140102,20140103,20140104,20140105,20140106,20140107,20140108)

val xsMap = ((1 to (xs.length + 1))
    zip xs.map(valueAtIndex => "s://" + valueAtIndex)).toMap

这不会特别快,但它很简单而且很有意义。 注意:我只测试了新的 scala3 编译器:dotty。我使用的Scala版本是3.0.1。