Search code examples
scalacollectlistbuffer

How to create listBuffer in collect function


I tought that List is enough but I need to add element to my list.

I've tried to put this in ListBuffer constructor but without result.

  var leavesValues: ListBuffer[Double] =
    leaves
      .collect { case leaf: Leaf => leaf.value.toDouble }
      .toList

Later on I'm going to add value to my list so my expected output is mutable list.

Solution of Raman Mishra

But what if I need to append single value to the end of leavesValues

  1. I can reverse but it's not good enough
  2. I can use ListBuffer like below but I believe that there is cleaner solution:

    val leavesValues: ListBuffer[Double] = ListBuffer()
    leavesValues.appendAll(leaves
      .collect { case leaf: Leaf => leaf.value.toDouble }
      .toList)
    

Solution

  •   case class Leaf(value:String)
    
      val leaves = List(Leaf("5"), Leaf("6"), Leaf("7"), Leaf("8") ,Leaf("9") )
    
      val leavesValues: List[Double] =
        leaves
          .collect { case leaf: Leaf => leaf.value.toDouble }
    
      val value = Leaf("10").value.toDouble
    
      val answer = value :: leavesValues
    
      println(answer)
    

    you can do it like this after getting the list of leavesValues you can prepand the value you want to add into the list.