← Back to Rust Course | Chapter 14: Closures, Iterators & Async | Lesson 3 of 6

map, filter और collect

map, filter, और collect आपको एक list से items transform, select, और आखिर में gather करने देते हैं, एक समय में एक clean step।
Syntax
rust
let result: Vec<Type> = collection
    .iter()
    .map(|x| expression)
    .filter(|x| condition)
    .collect();

Transforming with map

.map() किसी iterator के हर element पर एक closure apply करता है, original collection modify किए बिना transformed results का एक नया iterator produce करते हुए।

उदाहरण: Transforming with map

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `numbers`, set to `vec![1, 2, 3, 4]`
    let numbers = vec![1, 2, 3, 4];
    // Declare an immutable variable `squared` (a `Vec<i32>`), set to `numbers.iter().map(|n| n * n).collect()`
    let squared: Vec<i32> = numbers.iter().map(|n| n * n).collect();
    // Print "{:?}" to the console, substituting in `squared` (with a trailing newline)
    println!("{:?}", squared);
}

Selecting with filter

.filter() सिर्फ उन elements को रखता है जिनके लिए दिया closure true return करता है, बाकी सब कुछ resulting iterator से discard करते हुए।

उदाहरण: Selecting with filter

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `numbers`, set to `vec![1, 2, 3, 4, 5, 6]`
    let numbers = vec![1, 2, 3, 4, 5, 6];
    // Declare an immutable variable `evens` (a `Vec<&i32>`), set to `numbers.iter().filter(|&&n| n % 2 == 0).collect()`
    let evens: Vec<&i32> = numbers.iter().filter(|&&n| n % 2 == 0).collect();
    // Print "{:?}" to the console, substituting in `evens` (with a trailing newline)
    println!("{:?}", evens);
}

Gathering Results with collect

.collect() एक iterator consume करता है और इसके elements को एक concrete collection type में gather करता है, जैसे Vec<T> या एक String, context या एक explicit type annotation से inferred।

उदाहरण: Gathering Results with collect

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `words`, set to `vec!["Rust", "is", "fun"]`
    let words = vec!["Rust", "is", "fun"];
    // Declare an immutable variable `joined` (a String), set to `words.iter().map(|w| w.to_uppercase()).collect::<Vec<String>>().join(" ")`
    let joined: String = words.iter().map(|w| w.to_uppercase()).collect::<Vec<String>>().join(" ");
    // Print "{}" to the console, substituting in `joined` (with a trailing newline)
    println!("{}", joined);
}

Chaining map and filter Together

.map() और .filter() को sequence में chain किया जा सकता है ताकि एक multi-step transformation clearly और efficiently express हो, क्योंकि दोनों lazy हैं और सिर्फ .collect() pipeline consume करने पर चलते हैं।

उदाहरण: Chaining map and filter Together

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `numbers`, set to `vec![1, 2, 3, 4, 5, 6, 7, 8]`
    let numbers = vec![1, 2, 3, 4, 5, 6, 7, 8];
    // Declare an immutable variable `result` (a `Vec<i32>`), set to `numbers.iter().filter(|&&n| n % 2 == 0).map(|n| n * 10).collect()`
    let result: Vec<i32> = numbers.iter().filter(|&&n| n % 2 == 0).map(|n| n * 10).collect();
    // Print "{:?}" to the console, substituting in `result` (with a trailing newline)
    println!("{:?}", result);
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. एक chain के आखिर में .collect() (या कोई दूसरा consuming method) call करना भूल जाना, क्योंकि अकेले .map()/.filter() एक lazy iterator produce करते हैं, एक final collection नहीं।
  2. .collect() के लिए target type annotate न करना जब यह infer नहीं किया जा सके, एक ambiguous type के बारे में एक compile error की ओर ले जाते हुए।
  3. .map() के बाद .filter() chain करना जब पहले filter करना उन elements transform करने से बचाता जो बस फेंक दिए जाएंगे।
चैप्टर सारांश
  • .map(closure) iterator के हर element को transform करता है, transformed values का एक नया iterator produce करते हुए।
  • .filter(closure) सिर्फ उन elements को रखता है जिनके लिए closure true return करता है।
  • .collect() एक iterator consume करता है और इसके items को एक concrete collection में gather करता है, जैसे Vec<T>।
  • ये तीन methods आमतौर पर एक पूरी data transformation pipeline को concisely express करने के लिए एक साथ chained होते हैं।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.