개발 일기

Filtering 본문

컴퓨터 언어/kotlin

Filtering

이건욱

Filtering

Collection에서 Filter에서는 lambda 함수를 가질수가 있습니다.

lambda 함수에서는 return 값을 true / false를 가질수가 있습니다.

 

가장 기본적인 filtering 함수는 filter() 입니다.

filter에서는 각각의 요소에 조건에 맞는 값으로 새로운 Collection을 만듭니다.

 

[예시]

val numbers = listOf("one", "two", "three", "four")
val longerThan3 = numbers.filter { it.length > 3 }
println(longerThan3)

val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key11" to 11)
val filteredMap = numbersMap.filter { (key, value) -> key.endsWith("1") && value > 10}
println(filteredMap)


[three, four]
{key11=11}

 

 

filterIndexed

각각의 요소들에 포지션에 대한 값이 필요하다면 filterIndexed() 을 사용하면 됩니다.

filterNot

Collection filter에 조건이 false일 경우에 포함시키고 싶은 경우에는 filterNot()을 통해서 하실수가 있습니다.

val numbers = listOf("one", "two", "three", "four")

val filteredIdx = numbers.filterIndexed { index, s -> (index != 0) && (s.length < 5)  }
val filteredNot = numbers.filterNot { it.length <= 3 }

println(filteredIdx)
println(filteredNot)

[two, four]
[three, four]

 

filterIsInstance

filter했을 때 주어진 타입에 해당하는 값만 출력을 합니다. (filterIsInstance)

val numbers = listOf(null, 1, "two", 3.0, "four")
println("All String elements in upper case:")
numbers.filterIsInstance<String>().forEach {
    println(it.toUpperCase())
}

All String elements in upper case:
TWO
FOUR

filterNotNull()

filter 조건이 각각의 요소가 Null이 아닐 경우에 출력합니다. (filterNotNull)

val numbers = listOf(null, "one", "two", null)
numbers.filterNotNull().forEach {
    println(it.length)   // length is unavailable for nullable Strings
}

Partitioning()

filter 조건이 True 일때 매칭된 값과 매칭되지 않는 값을 두개로 나뉘어서 값이 주어 집니다. (partition)

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

println(match)
println(rest)

Testing predicates

- any() 최소한 하나이상 조건이 만족하면 return true 아니면 false 합니다.

- none() 조건이 하나라도 매칭이 안될 경우에는 return true 아니면 false 합니다.

- all() 모든 값에 대한 조건에 만족하면 return true 아니면 false 합니다.

val numbers = listOf("one", "two", "three", "four")

println(numbers.any { it.endsWith("e") })
println(numbers.none { it.endsWith("a") })
println(numbers.all { it.endsWith("e") })

println(emptyList<Int>().all { it > 5 })   // vacuous truth

true
true
false
true
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

'컴퓨터 언어 > kotlin' 카테고리의 다른 글

Grouping  (0) 2020.05.27
plus and minus Operators  (0) 2020.05.26
Collection Transformations  (0) 2020.05.22
Sequences  (0) 2020.05.21
Ranges  (0) 2020.05.21
Comments