LoginSignup
0
1

More than 1 year has passed since last update.

Go言語で重複する要素を取り除く方法

Last updated at Posted at 2023-03-02

はじめに

Go言語での重複処理ってどうやって書くんだろう?!ということで調べてみました。
1つの配列、2つの配列の比較でコードを書いてみる。

1つの配列の中での重複処理の場合

下記のようなコードがあった場合の重複処理の流れをGo言語で説明します。
重複しているのはabc123の値です。

userIDs := []string{"abc123", "def456", "ghi789", "abc123"}
userIDsMap := make(map[string]bool)
uniqUserIDs := [] string{}

for _, id := range userIDs {
    if !userIDsMap[id] {
        userIDsMap[id] = true
        uniqUserIDs = append(uniqUserIDs, id)
    }
}

fmt.Printf("%v", uniqUserIDs) // ["abc123", "def456", "ghi789"]

配列2つの比較して重複処理をする場合

下記のようなコードがあった場合の重複処理の流れをGo言語で説明します。
重複しているのはabc123の値です。

このコードでは、重複を除いた要素をマップに格納することができます。
これは、マップのキーに同じ値を2回追加しようとする場合、最初のキーの値が上書きされるためです。マップは、キーがユニークである必要があるため、同じキーを2度追加することはできません。

userIDs := []string{"abc123", "def456", "ghi789", "abc123"}
chatIDs := []string{"jkl012", "mno345", "abc123", "pqr678"}

chatIDMap := make(map[string]bool)
for _, userID := range userIDs {
    chatIDMap[userID] = true
}
for _, chatID := range chatIDs {
    chatIDMap[chatID] = true
}

chatIDList := make([]string, 0, len(chatIDMap))
for chatID := range chatIDMap {
    chatIDList = append(chatIDList, chatID)
}

for chatID := range chatIDMap {
    fmt.Printf("chatIDMap: %s\n", chatID)
}

出力結果は以下のようになります。

chatIDMap: abc123
chatIDMap: def456
chatIDMap: ghi789
chatIDMap: jkl012
chatIDMap: mno345
chatIDMap: pqr678

abc123 という要素が userIDschatIDs の両方に含まれているため、重複しています。
しかし、chatIDMap では、 abc123 のキーは1つだけであり、それに対応する値は true となっています。
重複した要素が除外され、ユニークな要素のみがマップに格納されることになります。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1