Code Logo

Filter Map with Iterator Chain

Published at25 Jul 2026
Rust Collections Medium 0 views
Like0

Write a Rust function that takes a vector of integers and returns a new vector containing only the even numbers, each doubled, using an iterator chain with .iter(), .filter(), .map(), and .collect(). This demonstrates Rust's zero-cost iterator abstraction that is central to idiomatic Rust programming.

Iterator chains are a hallmark of Rust's functional style. The .iter() method creates an iterator over references to the elements. .filter() takes a closure that returns true for elements to keep (checking x % 2 == 0 for evens). .map() transforms each kept element (doubling with x * 2). .collect() gathers the results into a new Vec. This chain reads like a pipeline: take the data, filter it, transform it, collect it.

Rust's iterator API is zero-cost: the chain compiles to the same efficient code as a hand-written loop, with no runtime overhead from closures or abstractions. The type system ensures that each stage of the chain produces the correct types, catching errors at compile time.

Time complexity is O(n) where n is the input length, as each element is visited once by the chain. Space complexity is O(k) where k is the number of filtered elements. The collect() method allocates a new vector for the results.

Edge cases include empty vectors (return empty vector), all-odd vectors (filter removes everything, return empty), all-even vectors (all pass filter), and negative numbers (the modulo operator handles negatives correctly).

Example Input & Output

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

No evens, empty result

Example 2
Input
[]
Output
[]
Explanation

Empty input

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

Filter evens, then double

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

Evens with negatives and zero

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

All evens, double each

Algorithm Flow

Recommendation Algorithm Flow for Filter Map with Iterator Chain
Recommendation Algorithm Flow for Filter Map with Iterator Chain

Solution Approach

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

Best Answers

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