LoginSignup
3
0

More than 5 years have passed since last update.

kotlinのcollection入門

Posted at

collectionとは

collection: List/Set/Map
collectionには読み取り専用(値が変更できない)と更新可(値が変更可)が存在する

読み取り専用(値が変更できない): List/Set/Map
更新可(値が変更できる): MutableList/MutableSet/MutableMap

基本的なcollectionの使い方

//初期化
val list = listOf(1, 2, 3)
val set = setOf(1, 2, 3)
val map = mapOf(1 to 10, 2 to 20, 3 to 30)


//値の更新はvalでも行えるため、基本的にvalで定義する
val mutableList = mutableListOf(1, 2, 3)
val mutableSet = mutableSetOf(1, 2, 3)
val mutableMap = mutableMapOf(1 to 10, 2 to 20, 3 to 30)


//値の追加
mutableList.add(4)
mutableSet.add(4)
mutableMap.put(4, 40) 

//値の削除
mutableList.remove(2)
mutableSet.remove(2)
mutableMap.remove(2)
mutableMap.remove(2, 20)

よく使用する操作関数

filter

val list = mutableListOf(1,2,3)


val arraySize = list.filter { it == 2 }.size


/*  filter内のitは配列の要素{1,2,3}を示している
        今回はlistの中から2に等しい要素をlist型で返す
        実行結果はarraySize = 1となる   */

forEach/forEachIndexed

val list = mutableListOf(1,2,3)

list.forEach { element -> //{1,2,3}が順番に入ってくる
    Log.d("test", element.toString())
    //実行結果: 1, 2, 3
}


list.forEachIndexed { element, index ->
    Log.d("test", index.toString() + "番目:" +element.toString() )
    //実行結果:1番目:1, 2番目:2, 3番目:3
    //要素に対してindexを取得したい場合に使用する
}

flatmap

val list = mutablelistOf(mutableListOf(1,2,3), mutableListOf(4,5,6))
//[[1,2,3],[4,5,6]]

val flatList = list.flatmap {num -> num}

//[1,2,3,4,5,6]
//ネストの深いList構造を平坦にしてくれる

distinct

val list = mutableListOf(1,2,3,2,3)

val distinctList = list.distinct()
//実行結果:1
//重複している要素を削除してそれ以外の要素を残している

take

val list = mutableListOf(1,2,3,4,5,6)

val takeList = list.take(3)
//実行結果:[1,2,3]
//takeで指定した数の分だけ先頭から要素を抜き出す
//後ろから抜き出したい場合はtakeLast
3
0
1

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