首页 > 解决方案 > 如何在 collect 函数中创建 listBuffer

问题描述

我认为 List 就足够了,但我需要在我的列表中添加元素。

我试图把它放在 ListBuffer 构造函数中,但没有结果。

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

稍后我将为我的列表添加价值,因此我的预期输出是可变列表。

拉曼米什拉溶液

但是如果我需要将单个值附加到 LeavesValues 的末尾怎么办

  1. 我可以逆转,但还不够好
  2. 我可以像下面这样使用 ListBuffer 但我相信有更清洁的解决方案:

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

标签: scalacollectlistbuffer

解决方案


  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)

您可以在获取 LeavesValues 列表后执行此操作,您可以预先设置要添加到列表中的值。


推荐阅读