title: Scala collections: Is there a safe map operation?
body: <p>Let's say that I have a List (or the values in a Map), and i want to perform an operation on each item. But unfortunately, for whatever reason, this list of values can contain nulls. </p>
  
  <pre><code>scala&gt; val players = List("Messi", null, "Xavi", "Iniesta", null)
  players: List[java.lang.String] = List(Messi, null, Xavi, Iniesta, null)
  </code></pre>
  
  <p>In order to avoid blowing up with a NPE, i need to do the following:</p>
  
  <pre><code>scala&gt; players.filterNot(_ == null ).map(_.toUpperCase)
  res84: List[java.lang.String] = List(MESSI, XAVI, INIESTA)
  </code></pre>
  
  <p>Is there any better way of doing this?</p>
  
  <p>Ideally something like:</p>
  
  <pre><code>players.safeMap(_.toUpperCase)
  </code></pre>
  
  <p>On the <a href="https://groups.google.com/forum/?fromgroups#!topic/scala-language/NPy-jkIo9sY" rel="nofollow">scala-language mailing list</a>, Simon proposed this:</p>
  
  <pre><code>players.filter ( null !=).map(_.toUpperCase )
  </code></pre>
  
  <p>which is shorter version of my original take, and as short as you can get without a dedicated method.</p>
  
  <p>Even better, Stefan and Kevin proposed the method withFilter which will return a lazy proxy, so both operations can be merged.</p>
  
  <pre><code>players.withFilter ( null !=).map(_.toUpperCase )
  </code></pre>