Help us understand the problem. What is going on with this article?

kotlinのcollection入門

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
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away