【问题标题】:Add an element in listbuffer into a map (update a map)将 listbuffer 中的元素添加到地图中(更新地图)
【发布时间】:2016-08-16 01:18:37
【问题描述】:

我是 scala 的新手,我在具有这种结构的地图中有一个列表缓冲区:

class Person(var name: String, var age: Int,note: ListBuffer[Note])
class Note(
  email: String,
  note:  Int)

var m = Map[Tuple3[Int,Int,Int],Person]()

如何更新地图以将新元素添加到列表缓冲区中。

【问题讨论】:

  • 你可以试试
  • 已经尝试过,但没有机会。我想要的只是一个指南!因为我很困惑
  • 那么告诉我们你尝试了什么
  • m((1,1,1)) = (note= ListBuffer(email= "test@gmail.com", note= 2))

标签: scala


【解决方案1】:

您应该强烈考虑在 Scala 中使用 case 类 - 它们免费为您提供了很多好东西。假设您确实将您的类更改为案例类,以下将实现您想要的:

import scala.collection.mutable.ListBuffer

case class Note(email: String, note:  Int)
case class Person(var name: String, var age: Int,note: ListBuffer[Note])


val n1 = Note("foo@gmail.com", 4)

val c1 = Person("John", 20, ListBuffer(n1))

val m = scala.collection.mutable.Map[(Int,Int,Int), Person]()

m += ((1,1,1) -> c1)

val n2 = Note("bar@gmail.com", 40)

m += ((1,1,1) -> c1.copy(note = c1.note += n2))

println(m)

res1: scala.collection.mutable.Map[(Int, Int, Int),Person] = Map((1,1,1) -> Person(John,20,ListBuffer(Note(foo@gmail.com,4), Note(bar@gmail.com,40))))

【讨论】:

    【解决方案2】:

    单独创建一个 ListBuffer,其中包含任意数量的注释。然后简单地创建如下地图:

    val lb = scala.collection.mutable.ListBuffer(new Note("s@s.com",1), new Note("d@d.com",2))
    Map((1,2,3) -> new Person("samar",0,lb))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-10
      相关资源
      最近更新 更多