Code Logo

Count with filter().count()

Published at25 Jul 2026
Rust Collections Easy 0 views
Like0

Write a Rust function that takes a vector of integers and returns the count of even numbers using an iterator chain with .iter(), .filter(), and .count(). The count() method consumes the iterator and returns the number of elements that passed through the filter.

The iterator chain .iter().filter(|&&x| x % 2 == 0).count() is a concise and idiomatic Rust pattern. .iter() creates an iterator over references to the elements, .filter() keeps only elements matching the closure, and .count() consumes the iterator and returns the total. This functional approach is preferred over manual loops with counters in idiomatic Rust.

The count() method is a consuming adapter that iterates through all remaining elements and returns their count. It works on any iterator, not just filtered ones. After calling count(), the iterator is consumed and cannot be used again. This is an example of Rust's ownership system at work in the iterator API.

Time complexity is O(n) where n is the vector length, as each element must be checked by the filter. Space complexity is O(1) as no intermediate collection is created. The iterator chain is lazy: filter runs only as many elements as needed by count, but count needs all elements so every element is checked.

Edge cases include empty vectors (returns 0), all elements passing the filter (returns the vector length), no elements passing (returns 0), and negative numbers which are correctly handled by the modulo operator.

Example Input & Output

Example 1
Input
[1,3,5]
Output
0
Explanation

No evens

Example 2
Input
[2,4,6,8]
Output
4
Explanation

All even

Example 3
Input
[-2,-1,0,1,2]
Output
3
Explanation

Evens: -2, 0, 2

Example 4
Input
[1,2,3,4,5,6]
Output
3
Explanation

Three even numbers: 2,4,6

Example 5
Input
[]
Output
0
Explanation

Empty vector

Algorithm Flow

Recommendation Algorithm Flow for Count with filter().count()
Recommendation Algorithm Flow for Count with filter().count()

Solution Approach

fn solution(nums: Vec<i32>) -> usize {
    nums.iter().filter(|&&x| x % 2 == 0).count()
}

Best Answers

rust - Approach 1
fn solution(nums: Vec<i32>) -> usize {
    nums.iter().filter(|&&x| x % 2 == 0).count()
}