Home  >  Article  >  Backend Development  >  How to merge maps in Golang and avoid duplicate values?

How to merge maps in Golang and avoid duplicate values?

Barbara Streisand
Barbara StreisandOriginal
2024-10-30 12:32:03109browse

How to merge maps in Golang and avoid duplicate values?

Merging Maps in Golang

Combining multiple maps into a single merged map in Golang is a common task. Suppose you have three maps:

  • map1 = {"id": "id_1", "val": "val_1"}
  • map2 = {"id": "id_2", "val": "val_2"}
  • map3 = {"id": "id_1", "val": "val_3"}

The goal is to merge these maps based on the id key, resulting in:

  • result_map = {"id": "id_1", "val": {"val_1", "val_3"}, "id": "id_2", var: {"val_2"}}

Simple Merge

To merge the maps, you can iterate over each input map and append the values associated with each key to a slice 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

In some cases, you may want to avoid duplicate values in the merged map. To achieve this, check for duplicates 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>

Usage Example

<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]]

The above is the detailed content of How to merge maps in Golang and avoid 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