/** * Returns a list containing only elements matching the given [predicate]. */ public inline fun <T> Iterable<T>.filter(predicate: (T) -> Boolean): List<T> { return filterTo(ArrayList<T>(), predicate) }
샘플코드
1 2 3 4 5
val listOfOverThirtyFive = users.filter { it.age > 35 } println(listOfOverThirtyFive.toString())
결과 : [User(name=beanbroker, age=40), User(name=C, age=44)]
2. all
모든 데이터가 주어진 조건이 맞는지 안하는지 return true or fale
1 2 3 4 5 6 7 8 9 10
/** * Returns `true` if all elements match the given [predicate]. * * @sample samples.collections.Collections.Aggregates.all */ public inline fun <T> Iterable<T>.all(predicate: (T) -> Boolean): Boolean { if (this is Collection && isEmpty()) returntrue for (element in this) if (!predicate(element)) returnfalse returntrue }
샘플코드
1 2 3 4 5 6 7 8 9 10
val isOlderThan50 = users.all { it.age > 50 }
println(isOlderThan50)
val isYoungerThan50 = users.all { it.age <50 } println(isYoungerThan50)
결과 isOlderThan50 : false isYoungerThan50 : true
만약 users.all { it.age <40 } 이면 false를 리턴 모든 조건을 충족해야하기 때문에
3. any
하나의 데이터라도 주어진 조건에 맞는다면 true를 리턴
1 2 3 4 5 6 7 8 9 10
/** * Returns `true` if at least one element matches the given [predicate]. * * @sample samples.collections.Collections.Aggregates.anyWithPredicate */ public inline fun <T> Iterable<T>.any(predicate: (T) -> Boolean): Boolean { if (this is Collection && isEmpty()) returnfalse for (element in this) if (predicate(element)) returntrue returnfalse }
샘플코드
1 2 3 4 5 6 7 8 9 10 11
val isAnyOneOlderThan50 = users.any { it.age > 50 }
println(isAnyOneOlderThan50)
val isAnyOnYoungerThan50 = users.any { it.age <40 } println(isAnyOnYoungerThan50)
결과 isAnyOneOlderThan50 : false isAnyOnYoungerThan50 : true
4. count
설명이 불필요…
샘플코드
1 2 3 4 5
val countWhoIsYoungerThan35 = users.count{it.age < 35} println(countWhoIsYoungerThan35)
결과 : 4
5. find, findLast
조건에 맞는 첫번째 데이터 반환, 만약 조건에 맞는 엘리먼트가 없다면 null리턴
만약 맨 뒤에 엘리먼트릴 return받고 싶다면 findLast를 쓰자!
1 2 3 4 5 6 7
/** * 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) }
샘플코드
1 2 3 4 5 6 7 8 9 10 11 12 13
val someoneWhoseAgeis32 = users.find { it.age == 32 }
println(someoneWhoseAgeis32.toString())
val someoneWhoseAgeis26 = users.find { it.age == 26 }
println(someoneWhoseAgeis26.toString())
결과 someoneWhoseAgeis32 : User(name='A', age=32) someoneWhoseAgeis26 : null