List के Operations (head/tail/map/filter)
List operations lists के लिए तेज़ tools हैं: head पहला item देता है, tail बाकी देता है, map हर item बदल देता है, और filter सिर्फ वे रखता है जो आप चाहते हैं। यह एक factory line जैसा है जो हर toy को process करती है।
In this page:
Syntax
list.head
list.tail
list.map(x => expression)
list.filter(x => condition)
List Operations (head/tail/map/filter)
.head किसी list का पहला element return करता है (list खाली होने पर throw करता है), और .tail पहले वाले के बाद हर element को एक नई list के रूप में return करता है।
.map(f) हर element को transform करता है और results की एक नई list return करता है, और .filter(p) सिर्फ वे elements रखता है जो किसी predicate से मेल खाते हैं। ये immutable lists के साथ functionally काम करने के मूल building blocks हैं।
Warning:
किसी खाली list पर .head या .tail call करना NoSuchElementException/UnsupportedOperationException फेंकता है -- अगर अनिश्चित हों तो पहले .isEmpty जांचें या .headOption का उपयोग करें।
उदाहरण: List Operations (head/tail/map/filter)
object Main extends App {
val numbers = List(1, 2, 3, 4, 5)
println(numbers.head)
println(numbers.tail)
val doubled = numbers.map(n => n * 2)
val evens = numbers.filter(n => n % 2 == 0)
println(doubled)
println(evens)
}
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 पर
.headया.tailcall करना, जो एक exception फेंकता है;headOptionका उपयोग करें याisEmptyजांचें। - यह उम्मीद करना कि
maplist को बदल देगा, जबकि यह एक नई list return करता है और original वैसा ही रहता है। - ऐसे predicate के साथ
filterका उपयोग करना जो non-Boolean return करे, याn =>भूल जाना, जैसेnumbers.filter(n % 2 == 0)।
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: