Kotlin

코틀린 (4) 필터

tjddneva 2022. 4. 3. 14:39

필터에 대해 보자. 

 

fun main(){

    val decorations = listOf ("rock", "pagoda", "plastic plant", "alligator", "flowerpot")

    val eager = decorations.filter { it[0] =='p' }
    println("eager: $eager")

    println("-------------")

    val ints = listOf(1,2,3)
    println(ints.filter { n : Int -> n>0 })
    println(ints.filter{ n->n>0 })

    println("-------------")

    val filtered = decorations.asSequence().filter{it[0]=='p'}
    println("filtered: $filtered")
    val newList = filtered.toList()
    println("new list: $newList")

    println("-------------")

    val numbers = setOf(1, 2, 3)
    println(numbers.map { it * 3 })

    println("-------------")

    val numberSets = listOf(setOf(1, 2, 3), setOf(4, 5), setOf(1, 2))
    println(numberSets.flatten())

    println("-------------")

    val words = "The quick brown fox jumps over the lazy dog".split(" ")

    //convert the List to a Sequence
    val wordsSequence = words.asSequence()
    val lengthsSequence = wordsSequence
        .filter { it.length > 3 }
        .map { it.length }
        .take(4)

    println("Lengths of first 4 words longer than 3 chars")
    // terminal operation: obtaining the result as a List
    println(lengthsSequence.toList())
}

eager: [pagoda, plastic plant]
-------------
[1, 2, 3]
[1, 2, 3]
-------------
filtered: kotlin.sequences.FilteringSequence@3a03464
new list: [pagoda, plastic plant]
-------------
[3, 6, 9]
-------------
[1, 2, 3, 4, 5, 1, 2]
-------------
Lengths of first 4 words longer than 3 chars
[5, 5, 5, 4]

시퀀스를 만들어서 필터를 하면 리스트를 만들지 않고 런타임때 참조가 된다는 것을 알아두면 된다.