Can there be any reason to prefer filter+map
:
list.filter (i => aCondition(i)).map(i => fun(i))
over collect
?
I guess this is rather opinion based, but given the following definitions:
scala> val l = List(1,2,3,4)
l: List[Int] = List(1, 2, 3, 4)
scala> def f(x: Int) = 2*x
f: (x: Int)Int
scala> def p(x: Int) = x%2 == 0
p: (x: Int)Boolean
Which of the two do you find nicer to read:
l.filter(p).map(f)
or
l.collect{ case i if p(i) => f(i) }
(Note that I had to fix your syntax above, as you need the bracket and case
to add the if
condition).
I personally find the filter
+map
much nicer to read and understand. It's all a matter of the exact syntax that you use, but given p
and f
, you don't have to write anonymous functions when using filter
or map
, while you do need them when using collect.
You also have the possibility to use flatMap
:
l.flatMap(i => if(p(i)) Some(f(i)) else None)
Which is likely to be the most efficient among the 3 solutions, but I find it less nice than map
and filter
.
Overall, it's very difficult to say which one would be faster, as it depends a lot of which optimizations end up being performed by scalac
and then the JVM. All 3 should be pretty close, and definitely not a factor in deciding which one to use.