【问题标题】:How to create listBuffer in collect function如何在 collect 函数中创建 listBuffer
【发布时间】:2019-01-04 07:26:30
【问题描述】:

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

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

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

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

Solution of Raman Mishra

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

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

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

【问题讨论】:

  • 你可以不使用 Listbuffer value::leavesValues 来做到这一点。
  • 如果您有多个问题,请单独提问。
  • 示例如何在没有 listBuffer 的情况下执行此操作?

标签: scala collect listbuffer


【解决方案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)

你可以在得到 LeavesValues 列表后这样做,你可以预先将要添加到列表中的值。

【讨论】:

  • 如果我需要像 val answer = leavesValues :: value 一样将值放在 leavesValues 后面,假设 value 是单个元素
  • @MrNetroful 那么您有两个选择,您可以反转列表然后进行预处理,也可以使用 listBuffer 并执行 LeavesValue += value
  • 有没有办法在构造函数传递列表或通过收集创建ListBuffer
  • 您到底想做什么,请提出明确的问题,然后只有我们可以帮助您。
  • 以上已编辑答案
猜你喜欢
  • 2017-03-22
  • 2022-08-16
  • 1970-01-01
  • 2011-09-28
  • 2019-05-19
  • 1970-01-01
  • 2020-04-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多