Filtering retains items whose predicate returns true. In Kotlin, `filter` expresses this directly: give a collection a lambda that returns `Boolean`, and receive a new collection containing the matching elements. The selected elements keep their original type; filtering extracts rather than transforms them. section 6.1.1
fun main() {
val list = listOf(1, 2, 3, 4)
println(list.filter { it % 2 == 0 }) #1
// [2, 4]
}
This compact form keeps only even values. `it` is the current element, and the predicate is true only when its remainder after division by two is zero. section 6.1.1
Use filtering when the requirement is about eligibility: people older than 30, nonblank unread messages, or characters in an allowed range. A chain can filter first and then map the survivors, such as extracting names from qualifying `Person` values. This separates selection from transformation and makes the intended pipeline easy to read. section 6.1.1 section 1.2.3
println(people.filter { it.age > 30 }.map(Person::name))
// [Bob]
The first operation removes people who do not meet the age condition; `map(Person::name)` then converts the remaining people to names. section 6.1.1
Related forms extend the same predicate-based idea:
- `filterIndexed` receives both index and element, allowing selection based on position as well as value. section 6.1.1
- A predicate may be any lambda returning `Boolean`; `all`, `any`, and `none` use predicates to check collection-wide conditions rather than produce selected elements. section 6.3
- For large pipelines, sequences use the same operations lazily and avoid intermediate collections. section 6.3
How filtering works underneath
A simple string filter iterates through each character, calls the predicate, and appends only characters for which it returns true. For example, filtering `"ab1c"` with `it in 'a'..'z'` produces `"abc"`. This reveals the core contract behind collection filtering: test each input item and accumulate the accepted ones. section 10.1.2
































