Home  >  Article  >  Backend Development  >  How to Merge Multiple Maps in Golang While Avoiding Duplicate Values?

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

Susan Sarandon
Susan SarandonOriginal
2024-10-27 15:39:02834browse

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.

<code class="go">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
}</code>

Avoiding Duplicates:

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

<code class="go">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
}</code>

Testing:

<code class="go">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)</code>

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.

The above is the detailed content of How to Merge Multiple Maps in Golang While Avoiding Duplicate Values?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn