Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get keys from map in scala

Tags:

scala

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
  }
}

}

like image 548
user11853582 Avatar asked Jan 27 '26 01:01

user11853582


2 Answers

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
  1. Get the Keys in a sorted Seq.

  2. 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.

like image 181
pme Avatar answered Jan 29 '26 15:01

pme


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)

like image 30
Volty De Qua Avatar answered Jan 29 '26 15:01

Volty De Qua



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!