How to create listBuffer in collect function

倖福魔咒の 提交于 2019-12-12 01:18:05

问题


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)
    

回答1:


  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.



来源:https://stackoverflow.com/questions/54034675/how-to-create-listbuffer-in-collect-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!