프로그래밍 공부/Kotlin
Kotlin Collection 유용한 기능, 예시 코드(1) / filter, map, any, all, none
홀싀
2022. 1. 27. 03:43
728x90
Play.Kotlin 의 예시코드중 자주 볼 것들을 가져왔음...
출처 : https://play.kotlinlang.org/byExample/05_Collections/
Kotlin Playground: Edit, Run, Share Kotlin Code Online
play.kotlinlang.org
1. filter : 조건을 람다로넣어주면 모든 element 를 확인해 true 값만 들어간 collection 을 return
val numbers = listOf(1, -2, 3, -4, 5, -6) // 1
val positives = numbers.filter { x -> x > 0 } // 2
val negatives = numbers.filter { it < 0 } // 3
result
Numbers: [1, -2, 3, -4, 5, -6]
Positive Numbers: [1, 3, 5]
Negative Numbers: [-2, -4, -6]
2. map : collection 의 한 종류인 Map 과 다른것이다.... (왜 이름을 이렇게...?)
람다로 받은 변형을 모든 element에 적용시킨 collection 을 return
val numbers = listOf(1, -2, 3, -4, 5, -6) // 1
val doubled = numbers.map { x -> x * 2 } // 2
val tripled = numbers.map { it * 3 } // 3
result
Numbers: [1, -2, 3, -4, 5, -6]
Doubled Numbers: [2, -4, 6, -8, 10, -12]
Tripled Numbers: [3, -6, 9, -12, 15, -18]
3. any, all, none
: 셋은 Boolean 을 return 한다.
람다로 받은 식을 만족하는 element 가
any : 하나라도 true이면 true
all : 전부 true 이면 true
none : 하나도 없으면 true
를 return 한다.
any 만 예시를..
val numbers = listOf(1, -2, 3, -4, 5, -6) // 1
val anyNegative = numbers.any { it < 0 } // 2
val anyGT6 = numbers.any { it > 6 }
result
Numbers: [1, -2, 3, -4, 5, -6]
Is there any number less than 0: true
Is there any number greater than 6: false
모든 코드는 위 출처 사이트에서 확인할 수 있고
Kotlin Playground 에서 편집도 해볼 수 있다...
728x90