map, filter और reduce
map किसी collection के हर item को बदल देता है, filter सिर्फ वही रखता है जो आप चाहते हैं, और reduce उन्हें एक जवाब में निचोड़ देता है। साथ में वे एक factory line जैसे हैं जो toys को paint, sort, और pack करती है।
In this page:
Syntax
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
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)
}
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
- किसी खाली list पर
reduceका उपयोग करना, जो एक exception फेंकता है; किसी start value के साथfoldLeftयाreduceOptionका उपयोग करें। - यह उम्मीद करना कि
filteroriginal list को बदल देगा, जबकि यह एक नई list return करता है। - यह भूल जाना कि
reduce(_ - _)operands के order पर निर्भर करता है, इसलिए results आपकी उम्मीद से अलग होते हैं।
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: