.collectFirst()
over .collect().headOption
SC-P1011The collect()
method collects the elements that satisfy the specified predicate. Chaining it with headOption
returns the first element from this collection.
However, the collect operation here is inefficient as elements except the first one are discarded without use.
It is recommended that you instead use .collectFirst()
as:
Iteration is terminated as soon as the first element that satisfies the predicate is found, and,
No resources are allocated for the intermediate buffer.
nums.collect(_ % 2 == 0).headOption
nums.collectFirst(_ % 2 == 0)