2

Could someone suggest a best way to merge entries in map for below use case in scala (possibly without using loop)?

From

val map1 = Map(((1,"case0")->List(1,2,3)), ((2,"case0")->List(3,4,5)), ((1,"case1")->List(2,4,6)), ((2,"case1")->List(3)))

To

Map(((1,"nocase")->List(2)), ((2,"nocase")->List(3)))
7
  • 2
    How come you have Duplicate keys in a Map. Did you tried printing this map? It'll display/store latest keys only. Commented Mar 22, 2018 at 6:32
  • Thanks for pointing this out. Key is a tuple in my case. Edited the question. Commented Mar 22, 2018 at 6:38
  • Now you have to update your result also according to your key Commented Mar 22, 2018 at 6:43
  • @Learner yes. This is possible using a for loop. However I wanted to know if this can be achieved using flatMap or groupBy etc., Commented Mar 22, 2018 at 6:46
  • how is the input related to the expected output? Commented Mar 22, 2018 at 7:12

1 Answer 1

3

You can do it as follows:

map1.groupBy(_._1._1).map{case (key, elements) => ((key, "nocase"), elements.values.reduce(_ intersect _ ))}

With the group you group the elements by the first element of the key, then with the map, you build the new key, with the "nocase" string as in your example. With elements.value you get all the elements for the given keys and you can reduce them with the intersect you get the expected output

Output:

Map[(Int, String),List[Int]] = Map((2,nocase) -> List(3), (1,nocase) -> List(2))
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the answer. Curious to know if grouping can be done only for specific keys which matches a condition and not for all keys? Also instead of "nocase" in the above question, if I have to use either of "case0" or "case1" from the actual key, is it possible to achieve?
If you want to join by the whole key, you can do it just modifying the groupBy: map1.groupBy(._1).map{case (key, elements) => (key, elements.values.reduce( intersect _ ))}
Using ._1 would still apply grouping for all keys, but I wanted to exclude this grouping for certain keys.
Umm, i don't know if its possible to join only by certain keys. What you can do is join as is, and then filter out the undesired keys. But I don't know if that match your requirement
Thanks for your inputs.

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.