Hanbit the Developer

Kotlin Documentation | Retrieve single elements 본문

Mobile/Kotlin

Kotlin Documentation | Retrieve single elements

hanbikan 2023. 5. 24. 14:34

Kotlin Documentation 시리즈에 대해

Category: Standard library - Collections

문서 링크: https://kotlinlang.org/docs/collection-elements.html


Retrieve by position

*Set은 LinkedHashSet, SortedSet 등 구현 방식에 따라 순서가 바뀐다는 점에 유의하라.

  • elementAt(3)
  • elementAtOrNull(3)
  • elementAtOrElse(5) { index → “The value at $index is undefined” }
  • first()
  • last()

Retrieve by condition

  • first {}
  • last {}
  • firstOrNull {}: == find()
  • lastOrNull {}: == findLast()
val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.first { it.length > 3 })
println(numbers.last { it.startsWith("f") })

Retrieve with selector

val list = listOf<Any>(0, "1234", false)
// Converts each element to string and returns the first one that has required length
val longEnough = list.firstNotNullOf { item -> item.toString().takeIf { it.length >= 4 } }
println(longEnough)
1234

아래 두 코드는 같은 동작을 한다. 다만 firstNotNullOf()는 아이템을 찾을 수 없다면 NoSuchElementException을 던진다.

list.firstNotNullOf { item -> item }
list.first { item -> item != null }

Random element

val numbers = listOf(1, 2, 3, 4)
println(numbers.random())

빈 컬렉션에 호출할 경우 예외를 던진다. 같은 경우에 randomOrNull()을 쓰는 경우 예외를 던지는 대신 null을 반환한다.

Check element existence

  • contains()
  • containsAll()
val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.contains("four"))
println("zero" in numbers)

println(numbers.containsAll(listOf("four", "two")))
println(numbers.containsAll(listOf("one", "zero")))
true
false
true
false
  • isEmpty()
  • isNotEmpty()