scala - 如何在 collect 函数中创建 listBuffer
问题描述
我认为 List 就足够了,但我需要在我的列表中添加元素。
我试图把它放在 ListBuffer 构造函数中,但没有结果。
var leavesValues: ListBuffer[Double] =
leaves
.collect { case leaf: Leaf => leaf.value.toDouble }
.toList
稍后我将为我的列表添加价值,因此我的预期输出是可变列表。
但是如果我需要将单个值附加到 LeavesValues 的末尾怎么办
- 我可以逆转,但还不够好
我可以像下面这样使用 ListBuffer 但我相信有更清洁的解决方案:
val leavesValues: ListBuffer[Double] = ListBuffer() leavesValues.appendAll(leaves .collect { case leaf: Leaf => leaf.value.toDouble } .toList)
解决方案
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 列表后执行此操作,您可以预先设置要添加到列表中的值。
推荐阅读
- sockets - Python_Problem_with_socket_programming
- angular - 在初始视图/页面加载时禁用动画:Angular
- git - 为什么在 Github 中推送到远程存储库后,既不询问也不推送凭据?
- java - AndroidStudio/Java:根据条件设置文本
- wordpress - 是否可以通过可以发送到数据库的表从用户那里获取网站输入?
- json - 将多种数据类型的数组拆分为不同的数组
- node.js - 在node.js中逐行创建模块预处理文件并分享
- java - 等待 UI 线程在 Android 中完成操作
- python - 使用装饰器转换函数参数
- python - 匹配不同数据帧的值