← Back to Scala Course | Chapter 9: Functional Programming | Lesson 2 of 8

map, filter और reduce

map किसी collection के हर item को बदल देता है, filter सिर्फ वही रखता है जो आप चाहते हैं, और reduce उन्हें एक जवाब में निचोड़ देता है। साथ में वे एक factory line जैसे हैं जो toys को paint, sort, और pack करती है।

In this page:

  1. map, filter, reduce
Syntax
scala
val mapped = collection.map(x => expression)
val filtered = collection.filter(x => condition)
val reduced = collection.reduce((a, b) => expression)

map, filter, reduce

map(f) किसी collection के हर element को transform करता है और results की एक नई collection return करता है। filter(p) सिर्फ वे elements रखता है जो किसी predicate से मेल खाते हैं।

reduce(f) सभी elements को एक binary function को बार-बार apply करके एक single value में combine करता है, जैसे sum पाने के लिए किसी list को + से fold करना। ये तीनों functional collection processing के core building blocks हैं।

Note: किसी खाली collection पर reduce fail हो जाता है -- अगर collection खाली हो सकती है तो किसी initial value के साथ foldLeft/foldRight का उपयोग करें।

उदाहरण: map, filter, reduce

markup
object Main extends App {
  val numbers = List(1, 2, 3, 4, 5)

  val doubled = numbers.map(n => n * 2)
  val evens = numbers.filter(n => n % 2 == 0)
  val total = numbers.reduce((a, b) => a + b)

  println(doubled)
  println(evens)
  println(total)
}
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. किसी खाली list पर reduce का उपयोग करना, जो एक exception फेंकता है; किसी start value के साथ foldLeft या reduceOption का उपयोग करें।
  2. यह उम्मीद करना कि filter original list को बदल देगा, जबकि यह एक नई list return करता है।
  3. यह भूल जाना कि reduce(_ - _) operands के order पर निर्भर करता है, इसलिए results आपकी उम्मीद से अलग होते हैं।
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 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.