Reputation: 67987
How do I map a sequence of class instances to a sequence of Maps in Scala?
Assume that the instances are of the following type:
class Package(_name: String, _description: String, _homepage: String = null) {
var name: String = _name
var description: String = _description
var homepage: String = _homepage
}
And we have a sequence of instances of this type:
var packages = Seq(
new Package("A", "Package A", "https://github.com/package/a"),
new Package("B", "Package B")
)
How do I map packages
to a sequence of Maps?
The Maps should be equivalent to the following:
Seq(
("name" -> "A", "description" -> "Package A", "homepage" -> "https://github.com/package/a"),
("name" -> "B", "description" -> "Package B", "homepage" -> null)
)
Upvotes: 0
Views: 346
Reputation: 144126
Based on your edit you can do:
packages.map(p => Map(("name", p.name), ("description", p.description), ("homepage", p.homepage)))
Upvotes: 3
Reputation: 20285
To create a map of packages
with name
as the key and Package
as the value this would do.
scala> packages.map(p => p.name -> p).toMap
res7: scala.collection.immutable.Map[String,Package] = Map(A -> Package@c3cec2e, B -> Package@73b5c648)
Upvotes: 1