Teodorico Levoff Teodorico Levoff - 1 year ago 83
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
, I want to fill it with
ListBuffer[(String, Int)]

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

Answer Source

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]
    var i = 0
    while (i < n) {
      b += elem
      i += 1

The above implementation is for one dimensional data structure.