1

My goal is to create two maps with keys all from a Seq[String].

For example, given:

val keys = Seq("key1", "key2")

I would like to get:

val map1 = Map("key1" -> List("something I get using key1"), "key2" -> List("something I get using key2"))
val map2 = Map("key1" -> List("some other stuff I get using key1"), "key2" -> List("some other stuff I get using key2"))

I've got a solution as below, but, given how cluttered and long this solution is, I feel like there must be a better/cleaner/more Scala-like approach.

Is there something I can do better in my solution? Appreciate the help in advanced!

val test = Seq("a", "b")

val (map1, map2) = 
(for (key <- test) yield {
      ((key -> List("some stuff with key")), (key -> List("some other stuff with key")))
    }).unzip match {
      case (seq1: Seq[(String, List[String])], seq2: Seq[(String, List[String])]) => {
        (seq1.toMap, seq2.toMap)
      }
      case _ => (Map(), Map())
    }

EDIT: Dima's solution below is definitely what I will go with since it's much simpler/easier to read, but my question here is more of is there a Scala way to avoid running .map twice on the same set of seq.

2 Answers 2

3

Using unzip on a single call to map as follow, delivers two collections of tuples that can be treated as Map,

val (map1, map2) = keys.map ( k => (k -> op1(k), k -> op2(k)) ).unzip

Namely, map1.toMap and map2.toMap converts each collection of tuples to Map. This involves though the need for two iterations over keys, one from map, the other from unzip.

Sign up to request clarification or add additional context in comments.

2 Comments

Since keys is a Seq, map1 and map2 end up being Seq[(String, X]], so I'll have to call map1.toMap and map2.toMap individually, right?
@DKT imho yes, unless you use mutable maps that are constructed incrementally.
1

How about

val keys = Seq("key1", "key2")
val map1 = keys
   .map { k => k -> doThingsWith(k) }
val ma2 = keyes 
   .map { k => k -> doOtherThingsWith(k) }

2 Comments

Ya, this is definitely what I will end up using in the end if no better answers came up. I was just curious if Scala/FP offered a way to do this in one line (vs running .map twice on the same seq).
Honestly, I wouldn't do this in one line. This solution is the clearest.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.