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.
    – vindev
    Commented Mar 22, 2018 at 6:32
  • Thanks for pointing this out. Key is a tuple in my case. Edited the question.
    – Srivignesh
    Commented Mar 22, 2018 at 6:38
  • Now you have to update your result also according to your key
    – Learner
    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.,
    – Srivignesh
    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))
5
  • 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?
    – Srivignesh
    Commented Mar 22, 2018 at 10:53
  • 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 _ ))}
    – SCouto
    Commented Mar 22, 2018 at 10:56
  • Using ._1 would still apply grouping for all keys, but I wanted to exclude this grouping for certain keys.
    – Srivignesh
    Commented Mar 22, 2018 at 11:04
  • 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
    – SCouto
    Commented Mar 22, 2018 at 11:12
  • Thanks for your inputs.
    – Srivignesh
    Commented Mar 22, 2018 at 11:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.