← Back to Scala Course | Chapter 6: Collections Basics | Lesson 2 of 8

List के Operations (head/tail/map/filter)

List operations lists के लिए तेज़ tools हैं: head पहला item देता है, tail बाकी देता है, map हर item बदल देता है, और filter सिर्फ वे रखता है जो आप चाहते हैं। यह एक factory line जैसा है जो हर toy को process करती है।
Syntax
scala
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)

markup
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)
}
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 पर .head या .tail call करना, जो एक exception फेंकता है; headOption का उपयोग करें या isEmpty जांचें।
  2. यह उम्मीद करना कि map list को बदल देगा, जबकि यह एक नई list return करता है और original वैसा ही रहता है।
  3. ऐसे 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:

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.