Kotlin Bootcamp for Programmers 8. filters
https://codelabs.developers.google.com/codelabs/kotlin-bootcamp-functions/#5
Kotlin Bootcamp for Programmers 3: Functions
There's a lot in this lesson, especially if you're new to lambdas. A later lesson revisits lambdas and higher-order functions. Note: You may have noticed that in Kotlin, as in some other languages, there is more than one correct way to do things. Making co
codelabs.developers.google.com
Step 1: Create a filter
1. Hello.kt에서 listOf ()를 사용하여 최상위 레벨에 수족관 장식 목록을 정의
val decorations = listOf ("rock", "pagoda", "plastic plant", "alligator", "flowerpot")
2. 문자 'p'로 시작하는 요소만 출력하도록 변경합니다. 필터 조건의 코드는 중괄호 {}로되어 있으며 필터가 반복 될 때 각 항목을 참조합니다. 표현식이 true를 리턴하면 항목이 포함됩니다.
fun main() {
println( decorations.filter {it[0] == 'p'})
}
⇒ [pagoda, plastic plant]
Step 2: Compare eager and lazy filters
eager : 사용할 때 필터가 적용된 새로운 리스트 생성
lazy : 새로운 리스트를 만들지 않고 불릴 때 해당 리스트에 필터가 적용된 값을 리턴
코틀린의 filter는 eager 방식으로 작동되며 필터를 사용할 때마다 list를 새로 만듭니다.
필터를 lazy하게 만들기 위해서는 Sequence 를 사용할 수 있습니다.
1. Hello.kt에서 필터링 된 목록을 eager라는 변수에 할당
fun main() {
val decorations = listOf ("rock", "pagoda", "plastic plant", "alligator", "flowerpot")
// eager, creates a new list
val eager = decorations.filter { it [0] == 'p' }
println("eager: " + eager)
2. Sequence with asSequence()
// lazy, will wait until asked to evaluate
val filtered = decorations.asSequence().filter { it[0] == 'p' }
println("filtered: " + filtered)
필터 결과를 시퀀스로 반환하면 필터링 된 변수에 new List가 포함되지 않습니다. List에 적용될 필터 옵션을 기억하고 있다가 시퀀스의 요소에 액세스 할 때마다 필터가 적용되고 결과가 반환됩니다.
3. toList ()를 사용하여 시퀀스를 List로 변환하여 시퀀스를 강제로 실행합니다
// force evaluation of the lazy list
val newList = filtered.toList()
println("new list: " + newList)
4. 프로그램을 실행하고 출력을 확인합니다.
⇒ eager: [pagoda, plastic plant]
filtered: kotlin.sequences.FilteringSequence@386cc1c4
new list: [pagoda, plastic plant]
시퀀스 및 lazy 작업을 시각화하려면 map () 함수를 사용하십시오. map () 함수는 시퀀스의 각 요소에 대해 간단한 변환을 수행합니다.
5. 위와 동일한 장식 목록을 사용하여 아무 것도 수행하지 않는 map ()으로 변환하고 전달 된 요소를 간단히 반환하십시오. println ()을 추가하여 요소에 액세스 할 때마다 표시하고 시퀀스를 lazyMap이라는 변수에 지정하십시오.
val lazyMap = decorations.asSequence().map {
println("access: $it")
it
}
6. lazyMap을 출력하고 first ()를 사용하여 lazyMap의 첫 번째 요소를 출력 한 다음 lazyMap을 List로 변환하여 출력하십시오.
println("lazy: $lazyMap")
println("-----")
println("first: ${lazyMap.first()}")
println("-----")
println("all: ${lazyMap.toList()}")
7. 프로그램을 실행하고 출력을 관찰하십시오. lazyMap을 인쇄하면 Sequence에 대한 참조 만 출력됩니다. 내부 println ()은 호출되지 않습니다. 첫 번째 요소를 출력하면 첫 번째 요소에만 액세스합니다. 시퀀스를 목록으로 변환하면 모든 요소에 액세스합니다.
⇒ lazy: kotlin.sequences.TransformingSequence@5ba23b66
-----
access: rock
first: rock
-----
access: rock
access: pagoda
access: plastic plant
access: alligator
access: flowerpot
all: [rock, pagoda, plastic plant, alligator, flowerpot]
8. 맵을 적용하기 전에 원래 필터를 사용하여 새 시퀀스를 만듭니다. 결과를 출력하십시오.
val lazyMap2 = decorations.asSequence().filter {it[0] == 'p'}.map {
println("access: $it")
it
}
println("-----")
println("filtered: ${ lazyMap2.toList() }")
9. 프로그램을 실행하고 추가 출력을 관찰하십시오. 첫 번째 요소를 얻는 것과 마찬가지로 내부 println ()은 액세스되는 요소에 대해서만 호출됩니다.
⇒
-----
access: pagoda
access: plastic plant
filtered: [pagoda, plastic plant]