1

I have the following mutable Hashmap in Scala:

HashMap((b,3), (c,4), (a,8), (a,2))

and need to be converted to the following:

HashMap((b,3), (c,4), (a,10))

I need something like reduceByKey function logic.

I added the code here

  def main(args: Array[String]) = {

    val m = new mutable.HashMap[String,Tuple2[String,Int]]()
    println("Hello, world")
    m.+=(("xx",("a",2)))
    m.+=(("uu",("b",3)))
    m.+=(("zz",("a",8)))
    m.+=(("yy",("c",4)))

    println(m.values)
  }
7
  • 2
    Keys in a hashmap are unique, so you do not have that mutable hashmap. By the time you've put those keys into a hashmap, you've already lost the older of them. Where do you get this data from? Can you get it as, perhaps, a list of tuples or something that allows duplicates? Commented May 6, 2022 at 15:51
  • Maybe you wanted to use a groupMapReduce before? Commented May 6, 2022 at 15:53
  • @SilvioMayolo I added the code and that was my output of println. Commented May 6, 2022 at 15:54
  • 1
    What purpose do the keys in the hashmap serve in your code example? It looks like you're grouping by a part of the value, not by the key? Is there any significance to the xx, yy, etc. part, or can we just get rid of that? Commented May 6, 2022 at 15:55
  • 1
    m.values.groupMapReduce(tuple => tuple._1)(tuple => tuple._2)((a, b) => a + b) Commented May 6, 2022 at 16:13

2 Answers 2

3

For pre 2.13 Scala versions you can try using groupBy with map:

m.values
  .groupBy(_._1)
  .mapValues(_.map(_._2).sum)
Sign up to request clarification or add additional context in comments.

Comments

2

It sounds like what you have is not a hashmap but m.values of type Iterable[Tuple2[String, Int]], which is more manageable. In that case, as hinted at in the comments, groupMapReduce does it all in one function. This function groups "matching" elements together, applies a transformation to each element, and then reduces the groups using a binary operation.

m.values.groupMapReduce(_._1)(_._2)(_ + _)

This says "Group the values by the first element of their tuple, then keep the second element (i.e. the number), and then add all of the numbers in each group". This produces a map from the first element of the tuple to the sum.

Map(a -> 10, b -> 3, c -> 4)

Note that this is a Map, not necessarily a HashMap. If you want a HashMap (i.e. for mutability), you'll need to convert it yourself.

2 Comments

I used Scala 2 and groupMapReduce cannot be resolved by compiler.
@MajidHajibaba groupMapReduce was introduced in Scala 2 =)

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.