How to combine all the values with the same key in Scala?

scala merge two maps
map values in scala
scala subtract two maps
scala map to list
scala groupby
scala immutable map
scala map find
scala create map

I have a map like :

val programming = Map(("functional", 1) -> "scala", ("functional", 2) -> "perl", ("orientedObject", 1) -> "java", ("orientedObject", 2) -> "C++")

with the same first element of key appearing multiple times.

How to regroup all the values corresponding to the same first element of key ? Which would turn this map into :

Map("functional" -> List("scala","perl"), "orientedObject" -> List("java","C++"))

UPDATE: This answer is based upon your original question. If you need the more complex Map definition, using a tuple as the key, then the other answers will address your requirements. You may still find this approach simpler.

As has been pointed out, you can't actually have multiple keys with the same value in a map. In the REPL, you'll note that your declaration becomes:

scala> val programming = Map("functional" -> "scala", "functional" -> "perl", "orientedObject" -> "java", "orientedObject" -> "C++")
programming: scala.collection.immutable.Map[String,String] = Map(functional -> perl, orientedObject -> C++)

So you end up missing some values. If you make this a List instead, you can get what you want as follows:

scala> val programming = List("functional" -> "scala", "functional" -> "perl", "orientedObject" -> "java", "orientedObject" -> "C++")
programming: List[(String, String)] = List((functional,scala), (functional,perl), (orientedObject,java), (orientedObject,C++))

scala> programming.groupBy(_._1).map(p => p._1 -> p._2.map(_._2)).toMap
res0: scala.collection.immutable.Map[String,List[String]] = Map(functional -> List(scala, perl), orientedObject -> List(java, C++))

How to combine all the values with the same key in Scala?, How to regroup all the values corresponding to the same first element of key ? Which would turn this map into : Map("functional" -> List("scala","perl"),  You can use combineByKey to track sum, count, min, max values, all in the same transformation. For that you need 3 functions: create combiner function - that will initialize the 'combined value' consisting of min, max etc merge values function - that will add another value to the 'combined value'

Based on your edit, you have a data structure that looks something like this

val programming = Map(("functional", 1) -> "scala", ("functional", 2) -> "perl",
("orientedObject", 1) -> "java", ("orientedObject", 2) -> "C++")

and you want to scrap the numerical indices and group by the string key. Fortunately, Scala provides a built-in that gets you close.

programming groupBy { case ((k, _), _) => k }

This will return a new map which contains submaps of the original, grouped by the key that we return from the "partial" function. But we want a map of lists, so let's ignore the keys in the submaps.

programming groupBy { case ((k, _), _) => k } mapValues { _.values }

This gets us a map of... some kind of Iterable. But we really want lists, so let's take the final step and convert to a list.

programming groupBy { case ((k, _), _) => k } mapValues { _.values.toList }

Scala Map: Combine keys with the same value? - scala - html, Here is a quick example in the REPL of a nested tuple scala> val t = ((1, 2), 3) t: Map[Int,Int] = Map(1 -> 3) If you want to set multiple values at once, you can do  Scala map is a collection of key/value pairs. Any value can be retrieved based on its key. Keys are unique in the Map, but values need not be unique. Maps are also called Hash tables. There are two kinds of Maps, the immutable and the mutable. The difference between mutable and immutable objects is that when an object is immutable, the object

You should try the .groupBy method

programming.groupBy(_._1._1)

and you will get

scala> programming.groupBy(_._1._1)
res1: scala.collection.immutable.Map[String,scala.collection.immutable.Map[(String, Int),String]] = Map(functional -> Map((functional,1) -> scala, (functional,2) -> perl), orientedObject -> Map((orientedObject,1) -> java, (orientedObject,2) -> C++))

you can now "clean" by doing something like:

scala> res1.mapValues(m => m.values.toList)
res3: scala.collection.immutable.Map[String,List[String]] = Map(functional -> List(scala, perl), orientedObject -> List(java, C++))

Merging Two Maps with Java 8, Learn different techniques for merging maps in Java 8. we'll examine different merging scenarios including maps having duplicate entries. with a value or the value is null, it associates the key with the given value. What the function does is take KV pairs and combine them (by Key) into KC pairs where C is a different type than V. One specifies 3 functions, createCombiner, mergeValue, mergeCombiners. The first specifies how to transform a type V into a type C, the second describes how to combine a type C with a type V,

Read the csv file and create a map that contains key and list of values.

 val fileStream = getClass.getResourceAsStream("/keyvaluepair.csv")
 val lines = Source.fromInputStream(fileStream).getLines

 var mp = Seq[List[(String, String)]]();
 var codeMap=List[(String, String)]();
 var res = Map[String,List[String]]();
 for(line <- lines )
 {
   val cols=line.split(",").map(_.trim())
   codeMap ++= Map(cols(0)->cols(1))
 }
 res = codeMap.groupBy(_._1).map(p => p._1 -> p._2.map(_._2)).toMap

Concatenate Two Maps in Scala, Difference between Kotlin and Scala · How to install Scala in Linux? Scala Byte +(x: Int): Int · Program to convert Java list of Shorts to a Vector in Scala It returns a single map by concatenating two maps but it separates the identical keys. How to sort a Scala Map by value · Scala Int <<(x: Int) method with example · How​  You have given a list of dictionaries, the task is to return a single dictionary with sum values with the same key. Let’s discuss different methods to do the task. Method #1: Using reduce () + operator. # Python code to demonstrate. # return the sum of values of dictionary. # with same keys in list of dictionary.

Since no one has put in the specific ordering he asked for:

programming.groupBy(_._1._1)
    .mapValues(_.toSeq.map { case ((t, i), l) => (i, l) }.sortBy(_._1).map(_._2))

How to join or merge two hashmaps in Java, putAll(HashMap) method which copies all of the mappings from the second So when we merge the maps in this way, for duplicate keys in map1 the value is  When using combineByKey values are merged into one value at each partition then each partition value is merged into a single value. It’s worth noting that the type of the combined value does not have to match the type of the original value and often times it won’t be. The combineByKey function takes 3 functions as arguments: A function that creates a combiner. In the aggregateByKey function the first

Scala and Spark for Big Data Analytics: Explore the concepts of , Thus, we need one operation for merging a V into a U and one operation for Ultimately, all pairs of (key-value) for the same Key are collected in the same  Merge a set of updates, insertions, and deletions based on a source table into a target Delta table. MERGE INTO [ db_name .] target_table [ AS target_alias ] USING [ db_name .] source_table [ < time_travel_version > ] [ AS source_alias ] ON < merge_condition > [ WHEN MATCHED [ AND < condition > ] THEN < matched_action > ] [ WHEN MATCHED [ AND < condition > ] THEN < matched_action > ] [ WHEN NOT MATCHED [ AND < condition > ] THEN < not_matched_action > ]

Class PairRDDFunctions<K,V>, Aggregate the values of each key, using given combine functions and a neutral "​zero aggregation (if a mapper can produce multiple items with the same key). Given two dictionary, the task is to combine the dictionaries such that we get the added values for common keys in resultant dictionary. Let’s see some of the methods to do the task. Check out this Author's contributed articles. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute

Map.merge(), Map.merge() - One method to rule them all Probably the most versatile operation in the key-value universe. And also Pre-Java 8 (read: pre-2014!) code was quite messy and the essence was lost in implementation details:. Final function is used to combine how to merge two accumulators (i.e. combiners) of a single key across the partitions to generate final expected result; Arguments are two accumulators (i.e. combiners) Merge results of a single key from different partitions; This function is similar to third argument (i.e. combOp) of aggregateByKey transformation.

Comments
  • Then you don't have a map. Have you tried printing the value of programming to the screen? Duplicate keys get overwritten, not added separately.
  • Yes, I simplified my problem too much. My question was about something slightly different. I just edited the question
  • The case statement can be replaced-by/reduced-to (_._1._1).
  • Yes, but I might die a little inside if I typed that anywhere outside of a codegolf contest. It seems like the Scala equivalent of (car (cdadr (cdr foo))).