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】Kotlin 基本文法:コレクション入門

Posted at

はじめに

Kotlin では コレクションAPI がとても充実しており、Java と互換性を持ちつつ「不変」「可変」を明確に区別できます。
本記事では List / Set / Map の基本から、分解宣言や高階関数を使った操作までを整理します。


1. Kotlin のコレクションの特徴

  • Java のコレクションと相互運用可能
  • 不変(読み取り専用)可変(変更可能) を区別
  • map, filter, fold など豊富な拡張関数を利用可能

2. List(順序あり・重複可)

読み取り専用

val numbers = listOf(1, 2, 3, 3)
println(numbers[0])   // 1
println(numbers.size) // 4

変更可能

val mutableNumbers = mutableListOf(1, 2, 3)
mutableNumbers.add(4)
mutableNumbers[0] = 10
println(mutableNumbers) // [10, 2, 3, 4]

3. Set(順序なし・重複不可)

読み取り専用

val set = setOf(1, 2, 2, 3)
println(set) // [1, 2, 3]

変更可能

val mutableSet = mutableSetOf(1, 2)
mutableSet.add(3)
mutableSet.remove(1)
println(mutableSet) // [2, 3]

4. Map(キーと値のペア)

読み取り専用

val map = mapOf(1 to "one", 2 to "two")
println(map[1]) // one

変更可能

val mutableMap = mutableMapOf(1 to "one")
mutableMap[2] = "two"
println(mutableMap) // {1=one, 2=two}

5. 分解宣言(Destructuring)

データクラスや Map を展開して使うことができます。

data class User(val id: Int, val name: String)

val user = User(1, "Anna")
val (id, name) = user
println(id)   // 1
println(name) // Anna

val map = mapOf(1 to "one", 2 to "two")
for ((key, value) in map) {
    println("$key -> $value")
}

6. 不変コレクションと可変コレクション

種類 読み取り専用 変更可能
List listOf mutableListOf
Set setOf mutableSetOf
Map mapOf mutableMapOf

原則は 不変コレクション を使い、必要に応じて可変にするのがベストプラクティス。


7. 高階関数でのコレクション操作

Kotlin のコレクションは関数型スタイルで簡潔に扱えます。

val numbers = listOf(1, 2, 3, 4, 5)

val doubled = numbers.map { it * 2 }           // [2, 4, 6, 8, 10]
val evens = numbers.filter { it % 2 == 0 }     // [2, 4]
val sum = numbers.fold(0) { acc, n -> acc + n } // 15

println(doubled)
println(evens)
println(sum)

まとめ

  • List: 順序あり、重複可
  • Set: 順序なし、重複不可
  • Map: キーと値のペア
  • 不変コレクション可変コレクション を区別する
  • 分解宣言 でデータクラスや Map を簡単に展開可能
  • map, filter, fold などの高階関数で関数型スタイルに処理できる

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?