kotlin - List

구태훈·2020년 6월 13일

kotlin

목록 보기
2/5

List는 kotlin Collection Type중의 하나로 순서가 있는 Element의 목록이다.

List 선언

var stringList:List<String> = listOf("a", "b", "c")
var stringList = listOf("a", "b", "c")
var mutableStringList = mutableListOf("a", "b", "c")

List 선언 : empty list

var emptyStringList = listOf<String>()
var emptyStringList:List<String> = listOf()

첫번쨰 element

someList.first()
someList[0]

list가 empty 인 경우 fisrt()는 NoSuchElementException, [0] 은 IndexOutOfException이 발생한다.

  • 안전한 코딩을 위해선 firstOrNull(), getOrElse(), getOrNull()을 사용 할 수 있다.
stringList.fistOrNull() ?: "default"
stringList.getOrNull() ?: "default" 
stringList.getOrElse(0) { "default" }

element 찾기

stringList.contains("a")
stringList.containsAll(listOf("a", "b"))

mutation

var mutableList = mutableListOf("a", "b", "c")
mutableList[0] = "A" // "A", "b", "c"
mutableList.add("d") // "A", "b", "c", "d"
mutableList.addAll(listOf("e","f") // "A", "b", "c", "d", "e", "f"
mutableList += "g" // "A", "b", "c", "d", "e", "f", "g"
mutableList += listOf("h", "i") // // "A", "b", "c", "d", "e", "f", "g", "h", "i"
mutableList -= "i" // "A", "b", "c", "d", "e", "f", "g", "h"
mutableList -= listOf("g", "h") // "A", "b", "c", "d", "e", "f"
mutableList.removeIf { it == "A" } // "b", "c", "d", "e", "f"
mutableList.clear() // []

Iteration

for in

for (a in somelist) {
	println("hello $a")
}

foreach

someList.foreach { println("hello $it") }
someList.foreachIndex { index, value -> 
	// statement 
}

destructiong

val someList = listOf(1,2,3)
val (first, second, third) = someList
val (fisst, _ , third) = someList
val (first) = someList 
profile
사업가를 꿈꾸는 소프트웨어 개발자.

0개의 댓글