ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Kotlin in Action - Lamda
    Kotlin 2019. 9. 24. 00:37

    본 내용은 Kotlin in Action 책을 읽고 공부한 내용을 정리하는 포스팅입니다.

     

    여러 Collection을 다루는 함수를 알아두면 원하는 data에 쉽게 접근할 수 있습니다.

     

    Filter 

    : 컬렉션 함수를 이터레이션 하면서 주어진 람다에 각 원소를 넘겨 True를 반환하는 원소만 모은다. 

    val list = listof(1,2,3,4)
    println(list.filter{it %2 ==0})
    //[2,4]

    결과는 컬렉션 원소 중에 Boolean값을 반환하는 Predicate로 ,
    true의 조건을 만족하는 원소만으로 이뤄진 새로운 컬렉션이다. 

     

    Map 

    : 컬렉션의 원소에 주어진 람다를 적용하여 새 컬렉션을 만든다. 

    val list = listof(1,2,3,4)
    println(list.map{it * it})
    //[1,4,9,16]

    groypBy 

    : 컬렉션의 어떤 원소의 특정에 따라 값을 분리하고 싶을 때 사용한다. 

    개인적으로 map으로 한번 더 filtering 해줘야 야무지게 사용할 수 있다고 생각한다. 

     

     val list = listOf<Int>(1,2,3,4,5,6,7)
        print(list.groupBy {
            it %2==0
        })
        //{false=[1, 3, 5, 7], true=[2, 4, 6]}
    

    여기에서 map으로 key 값을 감쌀것이냐에 따라서 값이 달라진다.  

     val list = listOf<Int>(1,2,3,4,5,6,7)
        print(list.groupBy {
            it %2==0
        }.map {
            it.key
        })
        //[false, true]
    

    value 

     val list = listOf<Int>(1,2,3,4,5,6,7)
        print(list.groupBy {
            it %2==0
        }.map {
            it.value
        })
        //[[1, 3, 5, 7], [2, 4, 6]]
    

    flatMap

    : 중첩된 컬렉션 안의 원소를 처리할 수 있다. 

    val arr = listof("abc","def")
    println(arr.flatMap{it.toList()})
    //[a,b,c,d,e,f]

     


     

    컬렉션 술어 

    - COUNT 

    : 원하는 조건의 컬렉션 원소의 개수를 반환한다. 

    val list = listOf<Int>(1,2,3,4)
        println(list.filter { it%2==0 }.count())
        //2

     

    - find 

    : 조건을 만족하는 첫전째 원소를 반환한다. (1개) 
    만족하는 원소가 전혀 없는 경우 null을 반환한다. 

     val list = listOf<Int>(1,2,3,4,5,6,7)
        println(list.filter { it%2==0 }.count())
    
        println(list.find {
            it>10
        })

    find의 내부 

    /**
     * Returns the first element matching the given [predicate], or `null` if no such element was found.
     */
    @kotlin.internal.InlineOnly
    public inline fun <T> Iterable<T>.find(predicate: (T) -> Boolean): T? {
        return firstOrNull(predicate)
    }

     

    - all 

    : 모든 원소가 이 술어를 만족한다면 true 

     val list = listOf<Int>(1,2,3,4,5,6,7)
    
        print(list.all {
            it>2
        })
        //false

     

    - any

    : 조건을 해당하는 원소가 1개라도 있다면 true

     val list = listOf<Int>(1,2,3,4,5,6,7)
    
        print(list.any {
            it>2
        })
        //true

     

    드모르간의 법칙을 들어봤다면 

    !all = any

    all = !any 

    라는 것을 알 수 있을 것이다.

     

    하지만 ! 부정의 의미는 잘 안 보일수 있기에 가독성이 떨어져 권장하지 않는 다고 한다.. 

     

    이 all,any 이 2개는 Predicate Type 으로 Return Type 은 Boolean 이다. 

     

     

    LIST

    'Kotlin' 카테고리의 다른 글

    [Kotlin] Data Class  (0) 2020.04.28
    [Kotlin]FoldRight && Fold  (0) 2019.12.27
    [Kotlin] Reference and Reflection  (0) 2019.10.22
    [Kotlin] Null Safety  (0) 2019.05.31
    [Kotlin]Basic Types  (0) 2018.09.21

    댓글

Designed by Tistory.