I have a problem with this code, the compiler tells me of an error in
for (key <- keys) type mismatch, found: Unit, required: Seq[String].
I'm getting the map keys in the wrong way? Thanks
def sorted(): Seq[String] = {
var sorting: Seq[String] = Seq()
var keys = db.keys.toSeq.sortWith(_ < _)
for (key <- keys) {
var names = db(key).sortWith(_ < _)
for (name <- names) {
sorting = sorting :+ name
}
}
}
I think doing this the functional way you can simplify this a lot:
def sorted(): Seq[String] =
for{
key <- db.keys.toSeq.sorted
value <- db(key).sorted
} yield value
Get the Keys in a sorted Seq.
Get the Values in a sorted Seq.
As with a for-comprehension this will flatMap these Seqs.
The result for: val db = Map("one" -> Seq("eins", "uno"), "two" -> Seq("zwei", "due"))
is: Vector(eins, uno, due, zwei)
Let me know if you don't understand something.
Your code implies you have a Map[String, Seq[String]]
So I would one-liner it:
db.keys.toSeq.sorted.flatMap(db(_).sorted)
(just add .toSeq if values are not already a Seq)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With