Teodorico Levoff Teodorico Levoff - 29 days ago 6
Scala Question

How to create a nested ListBuffer within another ListBuffer n times in Scala?

I have an empty

ListBuffer[ListBuffer[(String, Int)]]()
initialized like so, and given a number
n
, I want to fill it with
n
ListBuffer[(String, Int)]
.

For example, if
n=2
then I can initialize two
ListBuffer[(String, Int)]
within
ListBuffer[ListBuffer[(String, Int)]]()
if that makes any sense. I was trying to loop
n
times and use the insertAll function to insert an empty list but I didn't work.

Answer

use fill

fill is a standard Scala library function in order to fill a data structure with predefined elements. Its quite handy and save lot of typing.

ListBuffer.fill(100)(ListBuffer("Scala" -> 1))

Scala REPL

scala> import scala.collection.mutable._
import scala.collection.mutable._

scala> ListBuffer.fill(100)(ListBuffer("Scala" -> 1))
res4: scala.collection.mutable.ListBuffer[scala.collection.mutable.ListBuffer[(String, Int)]] = ListBuffer(ListBuffer((Scala,1)), ListBuffer((Scala,1)), ListBuffer((Scala,1)), ListBuffer((Scala,1)), ListBuffer((Scala,1)) ...

fill implementation in Standard library

def fill[A](n: Int)(elem: => A): CC[A] = {
    val b = newBuilder[A]
    b.sizeHint(n)
    var i = 0
    while (i < n) {
      b += elem
      i += 1
    }
    b.result()
  }

The above implementation is for one dimensional data structure.