在Scala中将ArrayBuffer [Map [String,String]]转换为Array [Map [String,String]]

时间:2018-07-26 03:21:59

标签: arrays scala arraybuffer

如何使用ArrayBuffer在Scala中将Maps(String,String)的{​​{1}}转换为Array的{​​{1}}?

Maps(String, String)

toArray()

2 个答案:

答案 0 :(得分:0)

ArrayBuffer是可变的数据结构。您可以调用.toArray将其转换为不可变的Array

scala> import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.ArrayBuffer

scala> ArrayBuffer(Map("x1" -> "x", "y1" -> "y"), Map("x2" -> "x", "y2" -> "y"))
res1: scala.collection.mutable.ArrayBuffer[scala.collection.immutable.Map[String,String]] = ArrayBuffer(Map(x1 -> x, y1 -> y), Map(x2 -> x, y2 -> y))

立即致电.toArray

scala> res1.toArray
res2: Array[scala.collection.immutable.Map[String,String]] = Array(Map(x1 -> x, y1 -> y), Map(x2 -> x, y2 -> y))

请参阅toArray的定义,该定义返回Array[B]

scala> res1.toArray
   def toArray[B >: scala.collection.immutable.Map[String,String]](implicit evidence$1: scala.reflect.ClassTag[B]): Array[B]

答案 1 :(得分:0)

如果您想要Scala的不可变数组和不可变Map,那么

import scala.collection.mutable.ArrayBuffer    
ArrayBuffer(Map("x1" -> "x", "y1" -> "y"), Map("x2" -> "x", "y2" -> "y")).toArray