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?

More than 3 years have passed since last update.

【Kotlin】コレクション(List, Set, Map)の特徴

0
Last updated at Posted at 2023-04-13

Kotlinで頻繁に使用されるコレクション(List, Set, Map)の特徴について、ラムダ式を用いて勉強する

List

要素の順序があり、重複した要素を持つことができるコレクション

Listの要素をラムダ式で処理する場合、forEach()メソッドを使用することができる

fun main() {
    val list = listOf("apple", "orange", "apple")
    list.forEach { println(it) }
}

Listの各要素を順番に取得し、それぞれの要素を引数としてラムダ式を実行している

出力結果
apple
orange
apple

Set

要素の順序がなく、重複した要素を持たないコレクション

Setの要素をラムダ式で処理する場合、forEach()メソッドを使用することができる

fun main() {
    val list = setOf("apple", "orange", "apple")
    list.forEach { println(it) }
}

Setの各要素を順番に取得し、それぞれの要素を引数としてラムダ式を実行している

出力結果
apple
orange

Map

キーのペアを持つコレクション
キーは重複を許さず、値は重複を許す

Mapの要素をラムダ式で処理する場合、forEach()メソッドを使用することができる

fun main() {
    val map = mapOf("apple" to 100, "orange" to 200, "banana" to 100)
    map.forEach { (key, value) -> println("$key: $value") }
}

Mapの各要素を順番に取得し、それぞれの要素を引数としてラムダ式を実行している
(ラムダ式の引数には、キーのペアを表すPairオブジェクトが渡される)

出力結果
apple: 100
orange: 200
banana: 100

キーの重複に注意

キーが重複した場合の挙動に注意が必要

fun main() {
    val map = mapOf("apple" to 100, "orange" to 200, "apple" to 300)
    map.forEach { (key, value) -> println("$key: $value") }
}

mapOf()関数で作成されたマップには、キーとしてappleが2回登録されているが、マップはキーの重複を許さない

そのため、2回目のappleの登録は無視され、値のみが上書きされる

出力結果
apple: 300
orange: 200
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?