scalalistappendlistbuffer

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


I have an emptyListBuffer[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.


Solution

  • 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.

    General suggestions

    Looks like you are using Scala like the Java way. This is not good. Embrace functional way for doing things for obvious benefits.

    Use immutable collections like List, Vector instead of mutable collections. Do not use mutable collections until and unless you have string reason for it.

    Same thing can be done using immutable List

    List.fill(100)(List("scala" -> 1))
    

    scala -> 1 is same as ("scala", 1)