Rust Guide > Documentation > Iterators > FilterMap

Introduction

The filter_map function in Rust is a powerful iterator adapter that allows you to filter and transform elements of an iterator in a single step. This function is particularly useful when you want to apply a transformation to each element and simultaneously filter out any elements that do not meet certain criteria.

Syntax


iterator.filter_map(|item| some_option)
The filter_map function takes a closure that returns an Option. Elements that return Some(value) are included in the resulting iterator, while elements that return None are filtered out.

Example Usage

Example 1: Filtering and Squaring Even Numbers

fn main() {
    let numbers = vec![1, 2, 3, 4, 5, 6];
    let result: Vec<i32> = numbers.into_iter().filter_map(|x| {
        if x % 2 == 0 {
            Some(x * x)
        } else {
            None
        }
    }).collect();
    println!("{:?}", result); // Output: [4, 16, 36]
}

Example 2: Converting Strings to Integers and Filtering Invalid Entries

fn main() {
    let strings = vec!["1", "two", "3", "four", "5"];
    let result: Vec<i32> = strings.into_iter().filter_map(|s| s.parse().ok()).collect();
    println!("{:?}", result); // Output: [1, 3, 5]
}

Example 3: Filtering and Transforming Option Values

fn main() {
    let options = vec![Some(1), None, Some(3), Some(4), None];
    let result: Vec<i32> = options.into_iter().filter_map(|x| x).collect();
    println!("{:?}", result); // Output: [1, 3, 4]
}

Example 4: Extracting File Extensions from Filenames

fn main() {
    let filenames = vec!["file1.txt", "file2", "file3.jpg", "file4.png"];
    let result: Vec<&str> = filenames.into_iter().filter_map(|name| {
        name.split('.').last().filter(|&ext| ext != name)
    }).collect();
    println!("{:?}", result); // Output: ["txt", "jpg", "png"]
}

Example 5: Filtering and Doubling Numbers Greater than a Threshold

fn main() {
    let numbers = vec![10, 15, 20, 25, 30];
    let result: Vec<i32> = numbers.into_iter().filter_map(|x| {
        if x > 20 {
            Some(x * 2)
        } else {
            None
        }
    }).collect();
    println!("{:?}", result); // Output: [50, 60]
}

See Also

  • filter - Filters elements of an iterator based on a predicate.
  • map - Transforms each element of an iterator using a function.
  • flat_map - Maps each element to an iterator and flattens the result.
  • partition - Splits an iterator into two collections based on a predicate.