0

I am new to Scala so I am a bit fighting with maps.

I have

val items = Seq[MyModel]

where MyModel (came from Java) contains getLang, getName and getMessage methods.

Now I need to fill up the

var loadedMessagesMap: Map[String, Map[String, String]] = ListMap.empty

to contain values grouped by lang in structure: lang -> (name -> message). Name property is unique. Thank you.

2 Answers 2

2

Maybe this will help you:

val result: Map[String, Map[String, Seq[String]]] = items.groupBy(_.getLang).map {
  case(lang, models) =>
    lang -> models.groupBy(_.getName).mapValues(_.map(_.getMessage))
}

It returns a Seq[String] because there might be several messages for the same language and name. Not sure how you want to handle that case.

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

2 Comments

Thank you. Getting there. I don't need to take care about multiple messages for same lang/name. This case will not happen (and they don't care about that too in FW backend). I did models.groupBy(_.getName).mapValues(_.map(_.getMessage).last) as a third row but I guess it is not the best solution:-)
@LukasJelinek It's fine. You can use .last or .head to get the a message from the list if you are sure the list will not be empty.
0

This should do the trick:

val models: Seq[MyModel] = ???
val mapped = models.map { model =>
  model.getLang -> Map(model.getName -> model.getMessage)
}.toMap

I hope this helps you.

9 Comments

Thank you, I am getting there just can you help me how to avoid this? Type mismatch; found : scala.collection.immutable.Map[String,(String, String)], required: Map[String,Map[String,String]]. I need to return the value in: Map[String, Map[String, String]] . Sorry, newbie:-)
Hmm, so you want also to group by name? You're getting the error because I actually built a map of string to tuples there.
I edited the answer now, it should do the trick; let me know if that's what you're looking for :)
Nice. I don't get the comment about replacing (model.getName, model.getMessage) though. Was that re an earlier version of the answer?
actually it is not necessary to group by name in my case, but the structure is needed in api I need to extend. The modification you did results only in one item, despite I have two models in Seq (same lang, different name and message).
|

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.