golang

Examples on How to Merge the Maps in Golang

In certain cases, we may need to merge multiple maps to create a consolidated map with combined data. This can be useful when we have overlapping keys or when we want to combine the information from different maps into a single map. Golang provides various ways to perform the merging map operation. In this article, we will consider the various methods to merge the maps in Go and effectively accomplish this operation.

Example 1: Merge the Maps in Golang Using the For Loop Method

We call the main() function after importing the necessary package. There, we initialize two maps: “m1” and “m2”. The “m1” variable map contains the string keys with corresponding integer values, while “m2” also has string keys with integer values.

Next, we print the contents of “m1” and “m2” using the fmt.Println function. It displays the values of both maps before the merging process. We then use the “range” keyword to build the “for” loop to go through the key-value combinations in “m1”.

In each iteration, the loop assigns the key to the variable “i” and the value to the variable “j”. Within the loop, the line m2[i] = j assigns the value of “j” from “m1” to the key “i” in “m2”. This effectively merges the values from “m1” into “m2”, overwriting any existing values in “m2” with the values from “m1” for the common keys.

package main
import (
  "fmt"
)
func main() {
  m1 := map[string]int{
    "A": 20,
    "B": 30,
 }
  m2 := map[string]int{
    "C": 25,
    "D": 35,
 }
  fmt.Println("First Map: ", m1)
  fmt.Println("Second Map: ", m2)
  for i, j := range m1 {
    m2[i] = y
  }
  fmt.Println("Merged Map: ", m2)
}

The output displays the merged map on the following console:

Example 2: Merge the Maps in Golang Using the Copy() Method

Additionally, we can perform the merge functionality on maps using the copy() function. The copy() function copies the map into another specified map by taking them as an argument.

package main
import (
    "fmt"
    "golang.org/x/exp/maps"
)

func main() {
    map1 := map[string]int{
        "One":   10,
        "Two":   20,
        "Three": 30,
    }
    map2 := map[string]int{
        "Two":   20,
        "Three": 30,
        "Four":  40,
        "Five":  50,
    }
    fmt.Println("Map First Value: ", map1)
    fmt.Println("Map Second Value: ", map2)
    maps.Copy(map1, map2)
    fmt.Println("Merged Map Results: ", map1)
}

We begin with the package declaration by importing the required packages: “fmt” for basic input/output functionality and “golang.org/x/exp/maps” for the “Copy” function. Then, we initialize two maps, “map1” and “map2”. Three key-value pairs—keys that are strings and values that are integers—are contained in the “map1” map variable.

The “map2” variable also has four key-value pairs, with the keys and the corresponding values. After that, we define the Copy() function from the golang.org/x/exp/maps package with “map1” and “map2” as arguments. This function merges the key-value pairs from “map2” into “map1”, overwriting any existing values in “map1” for the common keys.

The output is retrieved with the updated content of “map1” after the merge:

Example 3: Merge the Maps in Golang Using the Generic Method

Moreover, with generics, we can merge the maps using the MergeMaps() function that works with maps of any type, providing more flexibility and program reusability.

package main
import "fmt"
func main() {
MyMap1 := map[string]int{
"Alex": 5,
"Candice":  5,
}
MyMap2 := map[string]int{
"Alex": 5,
"Candice":  6,
"Harry":   7,
}
IntMergedMap := mergeMaps(MyMap1, MyMap2)
fmt.Printf("Merged int maps result: %v", IntMergedMap)
MyMap3 := map[string]bool{
"Alex": true,
"Candice":  true,
"Ben":  true,
}
MyMap4 := map[string]bool{
"Alex": true,
"Candice":  true,
"Andy":   true,
}
BoolMergedMap := mergeMaps(MyMap3, MyMap4)
fmt.Printf("Merged bool maps results: %v", BoolMergedMap)
}
func mergeMaps[K comparable, V any](MyMap1 map[K]V, MyMap2 map[K]V) map[K]V {
merged := make(map[K]V)
for key, val := range MyMap1 {
merged[key] = val
}
for key, val := range MyMap2 {
merged[key] = val
}
return merged
}

Here, we define two maps: “MyMap1” and “MyMap2”. These maps have string keys and integer values. Then, the “mergeMaps” function is declared. It is a generic function that is denoted by the “K” and “V” type parameters. “K” represents the type of the map keys and “V” represents the type of the map values.

The mergeMaps() function takes two maps, “MyMap1” and “MyMap2”, both of which have the same key and value types (K and V). It returns a new map that contains the merged key-value pairs from both input maps. Inside the “mergeMaps” function, we call a new merged map that is created using the “make” function. This map has the same key and value types as the input maps.

After that, we use a “range” loop to iterate the function through the “MyMap1” key-value pairs. It includes the item in the merged map for each key-value pair. The function then performs the same operation for “MyMap2”, adding its key-value pairs to the merged map. If a key already exists in the merged map, its value is updated with the value from “MyMap2”. When all the key-value pairs are merged, the merged map is returned from the mergeMaps() function.

Lastly, we call the mergeMaps() function twice: once with “MyMap1” and “MyMap2” (integer maps) and once with “MyMap3” and “MyMap4” (Boolean maps). The merged maps are assigned to “IntMergedMap” and “BoolMergedMap”, respectively.

The output showcases the two maps of different merged types in the following:

Example 4: Merge the Maps in Golang Using the User-Defined Method

However, we can merge two maps of custom struct types using the union which excludes the values with identical values and update the values based on a shared key in Golang.

package main
import     "fmt"
type emp struct {
    emp_id     int
    emp_name   string
    emp_salary int
}
type EmpMaps map[int]emp
func MapUnion(m1, m2 EmpMaps) EmpMaps {
    for k, l := range map1 {
        if x, y := m2[k]; y {
            l.emp_salary += m.emp_alary
        }
        m2[k] = l
    }
    return m2
}
func main() {
    m1 := EmpMaps{3: {10, "Katherine", 4000}, 1: {30, "Sammy",
                         2500}, 5: {50, "Jimmy", 2100}}
    m2 := EmpMaps{2: {20, "Emily", 3000}, 6: {40, "Elena",
                         1000}, 4: {10, "Katherine", 4000}, 3: {60, "Jenny", 2300}}
    res := MapUnion(m2, m1)
    fmt.Println(res)
}

Here, we define a custom struct type called “emp” which represents an employee. It has three fields: emp_id (integer), emp_name (string), and emp_salary (integer). Another custom type called “EmpMaps” is defined which is a map with integer keys and values of type “emp”.

After that, we declare the MapUnion() function which takes two “EmpMaps” maps (m1 and m2) as input and returns an “EmpMaps” map. Inside the “MapUnion” function, we use the loop to iterate over the key-value pairs in “m1” using the “range” keyword. The loop variable “k” represents the key and l represents the corresponding value of the “emp” struct.

There’s an “if” statement in the loop that checks if the “k” key also exists in “m2”. The program executes the conditional block if it is true. The value from “m2” corresponding to the “k” key is assigned to “x”, and the Boolean result of the “lookup” operation is assigned to “y” inside the “if” conditional block. If “y” is true (indicating that the key exists in “m2”), the code updates the emp_salary field of l by adding the value of emp_salary from “x”.

After updating l, it is assigned back to “m2” with the “k” key, effectively updating the value in “m2” if the key exists. Next, we call the main() function where two “EmpMaps” maps “m1” and “m2” are defined, each containing with multiple key-value pairs of type “emp”. The MapUnion() function is deployed with “m2” as the first argument and “m1” as the second argument. The merged map is assigned to “res”.

The maps of custom struct types are merged in the subsequent output:

Conclusion

According to the particular requirements, there are a number of ways to merge the maps in Go. Here, we explored two approaches to merge the maps which include a non-generic approach and a generic approach. The non-generic approach relies on conventional techniques, iterating over the maps and copying their key-value pairs into a new map.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content