0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

KotlinのPairとMapの使い分け

0
Posted at

Kotlinの似た型でPairとMapがあります。2つの違いと使い分けをまとめます。

Pairとは?

Pairは、2つの値を1組として扱う型です。

val pair: Pair<String, Int> = "Apple" to 100

println(pair.first)  // Apple
println(pair.second) // 100

2つの値を持ちfirstとsecondで取得します。マップのようにKeyによる検索や追加・削除はできません。

Mapとは?

Mapは、KeyとValueの1組を複数管理するコレクションです。

val prices: Map<String, Int> = mapOf(
    "Apple" to 100,
    "Orange" to 200,
    "Banana" to 150
)

println(prices["Apple"]) // 100

複数のKeyとValueを持つことができ、Keyを指定してValueを取得します。追加や削除や検索などができます。

PairとMapの使い分け方

Pairが向いている場面

  • 関数から2つの値を返したい
fun getSize(): Pair<Int, Int> {
    return 100 to 200
}

val (width, height) = getSize()
  • 処理の途中で2つの値をセットにしたい
val result = users.map {
    it.id to it.name
}
  • 座標や範囲など、2つの値を組み合わせたい
val point = 100 to 200

Mapが向いている場面

  • 設定値をKeyで管理する
val settings = mapOf(
    "theme" to "dark",
    "language" to "ja"
)

val theme = settings["theme"]
  • IDとデータを紐付ける
val userMap = users.associateBy { it.id }

val user = userMap[userId]
  • カテゴリごとにデータをまとめる
val grouped = users.groupBy {
    it.department
}
  • Keyから値を取得する
cache[userId] = user
val user = cache[userId]

Pairは一時的なデータの組み合わせ、MapはKeyを使ったデータ管理として使い分けると考えやすいです。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?