How to merge maps in Golang and avoid duplicate values?

Barbara Streisand
Release: 2024-10-30 12:32:03
Original
126 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

Output:

map[id_1:[val_1 val_3] id_2:[val_2]]
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!