Scala - 将数组转换为映射

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27023858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 06:43:09  来源:igfitidea点击:

Scala - converting array to map

scala

提问by user3279189

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.

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

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.

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

回答by Brian

This returns a Map[Int, Array[String]]. If you really want the values as a String, then use mapValues(_.mkString(","))on the result.

这将返回一个Map[Int, Array[String]]. 如果您确实希望将值作为 a 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))

回答by Noah

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)

回答by Don Mackenzie

Just another variation, this time avoiding zipWithIndex and the key value swap

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

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

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