0

How can I convert an ArrayBuffer of Maps(String,String) to an Array of Maps(String, String) in Scala using toArray()?

ArrayBuffer(Map("x1" -> "x", "y1" -> "y"), Map("x2" -> "x", "y2" -> "y"))

to

Array(Map("x1" -> "x", "y1" -> "y"), Map("x2" -> "x", "y2" -> "y"))
1
  • 2
    You can do arrBuff.toArray Commented Jul 26, 2018 at 3:34

2 Answers 2

3

ArrayBuffer is mutable data sturcture. you can call .toArray to convert it to immutable 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))

now call .toArray,

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

See the definition for toArray which returns Array[B],

scala> res1.toArray
   def toArray[B >: scala.collection.immutable.Map[String,String]](implicit evidence$1: scala.reflect.ClassTag[B]): Array[B]
Sign up to request clarification or add additional context in comments.

1 Comment

The toArray does not always work e.g. "Error not enough arguments for toArray. Unspecified value parameter evidence$2".
1

If you want Scala's immutable Array and immutable Map then

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.