3

Let I have big array of some structure (in example below Int is for simplicity) and want to filter this array and take first n elements. How can I do it?

Example:

val outerVar = 22

def filterFunction(a: Int): Boolean = {
  if (true/* some condition into this */) return false
  if (a > 12) return true
  if (a > 750) return false
  if (a == 42) return true
  if (a == outerVar) return true
  // etc conditions that can use context of outer space
  false
}

val n = 42
val bigArray = Array(1, 2, 3, 4, 5)
val result = bigArray.filter(element => {
  filterFunction(element)
})
//.limit(n) (something like)
// how to stop filling result after it will contain n elements?

1 Answers1

0

I believe, your predicate filterFunction is not going to do its work, since it always returns false.

Let's consider a toy example where we have an Array[Int] and we need to apply filter on it with predicate filterFunction so that the evaluation stops once n elements have been fetched:

scala> :paste
// Entering paste mode (ctrl-D to finish)

val array = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val filterFunction = (a: Int) => a > 5
val getLazy = (n: Int) => array.view.filter(filterFunction).take(n).toArray

getLazy(2)

// Exiting paste mode, now interpreting.

array: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
filterFunction: Int => Boolean = <function1>
getLazy: Int => Array[Int] = <function1>
res0: Array[Int] = Array(6, 7)

array.view.filter(filterFunction).take(n) becomes lazy expression (which is not evaluated right away) and toArray in fact runs the calculations.