Scala Iterable.partition
partition traverses a collection with a predicate and returns the matching and nonmatching groups as a pair.
A simple example
Iterable.partition
- Start with 1, 2, 3
- Do this Separate values at least 2
- Result Pass [2, 3], fail [1]
Syntax
val (passing, failing) = values.partition(predicate)
Run this example in Scala
Save the program as Lesson.scala. Use Scala 2.13.
scalac Lesson.scala
scala Lesson
Separate passing and failing records
A quality check divides records into those that pass its rule and those that fail. Preserve both result sets so the rejected records remain available to the person reviewing the batch.
object Lesson {
def main(args: Array[String]): Unit = {
val scores = List(49, 50, 80, 12)
val (passing, failing) = scores.partition(_ >= 50)
println(passing.mkString(","))
println(failing.mkString(","))
}
}
50,80 49,12
Equality with the threshold counts as a pass in this example. List preserves the original order inside each resulting group.
Scala documentation for Iterable.partition
Count packs on the delivery slip
A loading desk receives four item counts in sequence. The desk separates zero-quantity records for review. How many positive entries remain in the other group?
Review print quantities
A print room records four job quantities, including a cancelled job. The desk separates zero-quantity records for review. How many positive entries remain in the other group?