filter().headOption
as find()
23
24 def pickFirst1(arr: Array[Int], criteria: Int => Boolean): Int = arr.filter(criteria).head
25 def pickFirst2(arr: Array[Int], criteria: Int => Boolean): Option[Int] =
26 arr.filter(criteria).headOption27 def pickInAnOrder(arr: Array[Int], criteria: Int => Boolean): Array[Int] =
28 arr.sortWith(_ < _).filter(criteria)
29
The scala analyzer has determined that this collection method chain can be simplified into a single call to find()
.
Scala collections such as List
and ArrayBuffer
implement a number of processing methods -
1. .filter
- allows you to select elements from your collection based on the condition specified.
2. .find
- returns the first element that satisfies your condition as an Option
.
3. .headOption
- returns the first element from your collection as an Option
.
While .find
behaves in the exact same manner as .filter().headOption
, it performs slightly better as it terminates after finding the first element that satisfies your condition while .filter
continues to iterate through the entire collection. It is therefore suggested that you rewrite .filter().headOption
as .find
.
Bad practice
val firstEven = nums.filter(x => x % 2 == 0).headOption
Recommended
val firstEven = nums.find(x => x % 2 == 0)