Hanbit the Developer

Kotlin Documentation | Filter 본문

Mobile/Kotlin

Kotlin Documentation | Filter

hanbikan 2023. 5. 24. 14:12

Kotlin Documentation 시리즈에 대해

Category: Standard library - Collections

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


Filter by predicate

  • filter { it → true }
  • filterNot { it → true }: false인 아이템을 반환
  • filterIndexed { index, item → true }
  • filterIsInstance<String>(): String인 아이템을 반환
  • filterNotNull(): NotNull인 아이템을 반환

Partition

val numbers = listOf("one", "two", "three", "four")
val (match, rest) = numbers.partition { it.length > 3 }

println(match)
println(rest)
[three, four]
[one, two]

Test predicates

  • any { it.endsWith(”e”) }: e로 끝나는 게 하나라도 있으면 true
  • none { it.endsWith(”e”) }: e로 끝나는 게 하나도 없으면 true
  • all { it.endsWith(”e”) }: 모든 아이템이 e로 끝나면 true

without a predicate:

val numbers = listOf("one", "two", "three", "four")
val empty = emptyList<String>()

println(numbers.any())
println(empty.any())

println(numbers.none())
println(empty.none())
true
false
false
true