"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Merge Multiple Maps in Golang While Avoiding Duplicate Values?

How to Merge Multiple Maps in Golang While Avoiding Duplicate Values?

Published on 2024-11-08
Browse:703

How to Merge Multiple Maps in Golang While Avoiding Duplicate Values?

Merging Maps in Golang

Problem:
Merge multiple maps, preserving values associated with the same key across maps.

Initial Approach:

The provided code attempts to merge maps by iterating over each map, adding values to the result map based on matching keys. However, this approach does not handle duplicate values within the result map.

Simple Merge:

A revised merge function can be implemented to handle duplicates by appending values to slices associated with keys in the result map.

func merge(ms ...map[string]string) map[string][]string {
    res := map[string][]string{}
    for _, m := range ms {
        for k, v := range m {
            res[k] = append(res[k], v)
        }
    }
    return res
}

Avoiding Duplicates:

To avoid duplicates in the result map, the merge function can be modified to check for existing values before appending:

func merge(ms ...map[string]string) map[string][]string {
    res := map[string][]string{}
    for _, m := range ms {
    srcMap:
        for k, v := range m {
            // Check if (k,v) was added before:
            for _, v2 := range res[k] {
                if v == v2 {
                    continue srcMap
                }
            }
            res[k] = append(res[k], v)
        }
    }
    return res
}

Testing:

m1 := map[string]string{"id_1": "val_1"}
m2 := map[string]string{"id_2": "val_2", "id_1": "val_1"}
m3 := map[string]string{"id_1": "val_3"}

res := merge(m1, m2, m3)
fmt.Println(res)

Output:

map[id_1:[val_1 val_3] id_2:[val_2]]

This demonstrates the merging of maps, preserving values associated with the same key and avoiding duplicates.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3